분류 전체보기

python 메모

[pandas] excel로 저장할 때 IllegalCharacterError가 뜰 때

pandas DataFrame을 excel로 저장할 때 IllegalCharacterError 같은 에러가 뜰 때가 있다. 이때 openpyxl로 저장하는 부분을 df.to_excel("test.xlsx", engine='openpyxl') xlsxwriter로 바꿔서 사용하면 에러가 안뜬다. df.to_excel("test.xlsx", engine='xlsxwriter')

python 메모

[sqlite] cx.read_sql, pd.read_sql 속도비교

pandas로 sqlite3 파일에서 300백만개 정도 되는 row의 데이터를 읽어올 일이 있었다. 하지만 이건 속도가 너무 느리다. connectorx와 비교해보자. 1. 사용법 비교 (1) pandas import sqlite3 import pandas as pd local_file_path = "/absolute/path/to/sqlite3/db" conn = sqlite3.connect(local_file_path) to_read = pd.read_sql( "SELECT * FROM '{tbl_name}'".format(tbl_name=tbl_name), conn, parse_dates=['timestamp'] ) (2) connectorx import connectorx as cx local_f..

개발

[websocket] (1) python websocket 서버 생성 & 클라이언트 테스트

python websockets 라이브러리를 사용해서 아주 간단한 websocket 서버를 만들어볼 수 있다. [참고문서] https://websockets.readthedocs.io/en/stable/ 1. 서버 생성 import asyncio import time import websockets import datetime import multiprocessing as mp # create handler for each connection if __name__ == "__main__": async def handler(websocket, path): while True: await websocket.send("[*] M1 from SERVER 1 "+str(datetime.datetime.now())..

개발

[ubuntu] mpi4py 설치 시 에러

ubuntu에서 pip install mpi4py로 mpi4py를 설치할 때 다음과 같이 에러메세지가 나는 경우가 있다. .... error: Cannot compile MPI programs. Check your configuration!!! [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mpi4py Failed to build mpi4py ERROR: Could not build wheels for mpi4py, which is required to install pyproject.toml-based proje..

개발

[ChatGPT가 알려주는] overflow, underflow 파이썬 예시

Overflow and underflow are two concepts that refer to the limits of numerical representation in computing. They can happen in various programming contexts, including in Python, especially when dealing with floating-point numbers or integers that exceed the maximum or minimum size that can be represented. 1. Overflow Overflow occurs when a calculation produces a result that is larger than the max..

개발

[ubuntu] nohup 파일 생성 시 현재 날짜로 생기게 하기

nohup echo "hi" &> nohup$(date --iso).out & 이와 같이 $(date --iso)를 사용하면 현재 날짜를 기준으로 한 로그를 남길 수 있다.

python 메모

[matplotlib] 여러개의 다른 y축 그래프를 한 그래프에 그리기

같은 x축에 대해 서로 다른 y scale의 그래프를 그릴 일이 있다. 아래와 같이 그리면 된다. import matplotlib.pyplot as plt fig, ax = plt.subplots() fig.subplots_adjust(right=0.75) twin1 = ax.twinx() twin2 = ax.twinx() twin3 = ax.twinx() # Offset the right spine of twin2. The ticks and label have already been # placed on the right by twinx above. twin2.spines.right.set_position(("axes", 1.2)) twin3.spines.right.set_position(("axes"..

개발

[ubuntu] crontab 사용법 간단정리

1. Cron Job 등록 crontab -e로 job을 등록할 수 있다. # crontab -e 실행 후 아래 line 등록 # 매월 9일 21시 8분에 run.sh 실행 8 21 9 * * /home/user/.../run.sh # weekday(월-금) 매일 18시 0분에 run.sh 실행 0 18 * * 1-5 /home/user/.../run.sh 2. Cron Job 확인 crontab -l을 확인하면 등록한 job 목록을 보여준다. user@user-System-Product-Name:~/$ crontab -l MAILTO="" # Edit this file to introduce tasks to be run by cron. # # Each task to run has to be define..

개발

[ubuntu] 좀비 프로세스 죽이기(defunct)

ps -ef | grep defunct로 좀비 프로세스를 확인해보면 다음과 같이 나온다. 이때 34502가 parant process id인데 얘를 죽여주면 하위 프로세스들도 죽는다. sudo kill -9 34502 ps -ef | grep defunct user 32872 30725 0 14:49 pts/0 00:00:00 grep --color=auto defunct

python 메모

[python] list를 chunk로 나누는 방법들(메모)

ChatGPT가 알려준 리스트를 나누는 방법들을 정리해두고자 한다. 1. 리스트를 특정 크기로 자르기 def split_list_into_chunks(lst, chunk_size): """ Split a list into chunks of the specified size. Parameters: - lst: The list to be split. - chunk_size: The size of each chunk. Returns: A list of chunks, where each chunk is a sublist of the original list. """ return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)] my_list = [..

python 메모

[regex] 정규표현식 메모용

일하면서 사용했던 정규표현식을 정리해두고자 한다. 1. HTML에서 주석() 부분 찾기 HTML에서 주석 부분만 찾는 표현식이다. 정규표현식: python으로는 아래와 같이 사용할 수 있다. text = """ 이것은 주석이 아닙니다 """ import re text = re.sub(r'','', text) text >>>> '\n이것은 주석이 아닙니다\n\n' 2. HTML에서 공백인 부분 제거 BeautifulSoup을 사용해서 표를 파싱한 후 soup.prettify(formatter="html")를 하면 불필요한 공백이 많이 생성된다. 이때 2개 이상 이어진 공백에서 하나만 남기고 나머지 공백들을 제거하는 표현식이다. 정규표현식: \B\s+|\s+\B^ python으로는 아래와 같이 사용할 수 있..

python 메모

[websocket] 연결이 끊겼을 때 reconnect를 위한 방법들

파이썬에는 웹소켓 사용을 위한 websocket, websockets(두개가 다른 거다) 라이브러리가 있다. 웹소켓 연결이 끊겼을 때를 대비하기 위한 방법이 각각 다른데 이를 간단히 정리해두고자 한다. 1. websocket websocket 라이브러리는 pip install websocket-client로 설치할 수 있다. 공식 github에 가서 보면 아래와 같은 설명이 있다(링크). The WebSocketApp run_forever loop will automatically try to reconnect to an open WebSocket connection when a network connection... run_forever does not automatically reconnect if ..

python 메모

[GPU] pynvml 모듈로 gpu 사용량 체크하기

GPU 모니터링 툴이 별도로 없을 때 pynvml을 사용하여 GPU 사용량 정보 등을 로그로 남길 수 있는 방법을 정리하고자 한다. 1. GPU 정보 확인하기 import pynvml print("Driver Version:", pynvml.nvmlSystemGetDriverVersion()) >>>> Driver Version: 4xx.1xx.xx 2. GPU 사용량 체크하기 GPU가 여러 장 있을 때 GPU별 utilization, memory 사용량 평균을 다음과 같이 기록해둘 수 있다. from threading import Thread import numpy as np import torch .... if __name__ == "__main__": def schedule_gpu_memory_lo..

논문 및 개념 정리

[2023] The Wisdom of Hindsight Makes Language Models Better Instruction Followers

0. Abstract We consider an alternative approach: converting feedback to instruction by relabeling the original one and training the model for better alignment in a supervised manner 1. Introduction Human alignment를 위해 두 가지 정도의 방향성이 있음 Proximal Policy Optimization (PPO): rather complex, sensitive to hyperparameters, and requires additional training in the reward model and value network imitation ..

python 메모

[python] jsonl로 데이터 읽고 쓰기

json보다 jsonl이 편할 때는 파일로 데이터를 읽고 쓸 때이다. json은 데이터를 한꺼번에 불러와야 하지만 jsonl은 file 객체로 읽고 쓰기 때문에 a 모드를 지원한다. 즉, jsonl 파일에 데이터 한줄만 추가하는 형태로 사용할 수 있지만 json은 그게 안된다. 1. 데이터 쓰기 주의사항은 indent=4을 주게되면 저장된 파일에 newline이 생겨 읽을 때 에러가 뜬다. 이거 빼준다. import json d = { "a":[1,2,3], "b":[4,5,6,7], "C": "qwer", "D": "한글" } data_list = [d]*4 with open("test.jsonl", "a") as f: for data in data_list: f.write( json.dumps(dat..

Fine애플
'분류 전체보기' 카테고리의 글 목록