python 메모

python 메모

[pandas] duplicated()의 함정과 모든 중복 데이터 모으기

pandas를 쓰다가 중복된 데이터를 처리할 때 모든 중복 데이터를 확인하고 싶을 때가 있다. 이를 위한 방법을 정리하고자 한다. 1. duplicated()의 함정 아래와 같은 데이터가 있다고 하자. print(data.to_markdown()) >>>> | | class | age | good | |---:|:--------|------:|:-------| | 0 | a | 11 | True | | 1 | a | 10 | True | | 2 | b | 9 | True | | 3 | c | 9 | False | | 4 | c | 7 | False | | 5 | c | 7 | False | duplicated()를 사용하면 중복데이터 중 남겨둘 데이터 하나를 제외한 중복데이터만 보여준다. print(da..

python 메모

[jupyter] notebook 파일 cli로 중단없이 실행시키기

jupyter notebook은 접속 화면을 끄면 실행이 중단되는 부분이 있어서 아쉽다. 이를 우회하기 위해 notebook 파일을 작성하고 nohup, tmux 등으로 백그라운드에서 실행시키는 방법을 정리하고자 한다. 1. jupyter notebook 파일 작성하기 방법을 테스트하기 위해 matplotlib, tqdm 스크립트를 작성하고 cli_run_test.ipynb로 저장해두었다. 2. jupyter notebook cli로 실행 아래와 같이 jupyter nbconvert를 사용하면 되며 결과물로 cli_run_test.nbconvert.ipynb이 새로 생긴다. jupyter nbconvert --execute --to notebook cli_run_test.ipynb >>>> [NbConv..

python 메모

[numpy] np.take, np.take_along_axis

np.array 원소를 index에 따라서 가져오고 싶은 경우가 많이 있다. 이때 사용할 수 있는 방법들을 정리하고자 한다. 0. Index를 사용하는 경우 np.array에서 index만 뽑아오는 경우는 대표적으로 np.where, np.argsort, np.min, np.max 등이 있다. a = np.array([4, 3, 7, 9, 6, 8]) np.argsort(a) >>>> array([1, 0, 4, 2, 5, 3]) np.where(a>4) >>>> (array([2, 3, 4, 5]),) 1. np.take 원문에 보면 아래와 같이 설명되어 있다. Take elements from an array along an axis. When axis is not None, this function..

python 메모

[pandas] 셀의 모든 내용 출력하기

1. 셀 모든 내용 출력 pandas를 사용할 때 셀의 내용이 길면 잘려서 나오는게 기본 세팅이다(truncated). 셀의 모든 내용을 출력하고 싶으면 아래 설정을 사용하면 된다. import pandas as pd pd.set_option('display.max_colwidth', None) 2. 모든 row, column 출력 pandas.set_option('display.max_rows', None) # 항상 모두 출력 pandas.set_option('display.max_rows', 10) # 항상 10개만 출력 pandas.set_option('display.max_columns', None) # 항상 모두 출력 pandas.set_option('display.max_columns', 10..

python 메모

[예외처리] try, except, finally

파이썬 예외처리에 사용되는 구문을 정리하고자 한다. 1. try, except, finally a = dict() try: print('Hello World!') print(a['key']) except KeyError: print('KeyError 발생') except: print('다른 Error 발생') finally: print('수고하셨습니다') >>>> Hello World! KeyError 발생 수고하셨습니다 except 부분은 에러 종류별로 다르게 실행할 수 있도록 에러를 지정할 수 있으며, raise와 함께 별도의 에러를 만들 수도 있다. # define Python user-defined exceptions class Error(Exception): """Base class for ot..

python 메모

[transformers] tokenizer 결과

huggingface 라이브러리에서 제공하는 tokenizer 결과를 정리해본다. kakaobrain의 KOGPT모델을 사용하였다. 0. Tokenizer import torch from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained( 'kakaobrain/kogpt', revision='KoGPT6B-ryan1.5b-float16', # or float32 version: revision=KoGPT6B-ryan1.5b bos_token='[BOS]', eos_token='[EOS]', unk_token='[UNK]', pad_token='[PAD]', mask_token='[..

python 메모

[asyncio+aiohttp] 여러 API 비동기 호출 결과 얻기

python asyncio는 비동기 프로그래밍을 위해 python 3.4 버전에 추가된 내장 라이브러리이다. 그 이후로 계속 변화를 거치면서 사용법이 조금씩 달라졌는데, python 3.7을 기준으로 테스트해보았다. 0. Asyncio?, Aiohttp? 1) Asyncio 파이썬에서의 비동기 프로그래밍을 위한 asyncio 라이브러리는 HummingLab님의 글이나 DaleSeo님의 글에 매우 잘 설명이 되어 있다. 하나의 thread로 여러 요청에 응답하는 I/O bound한 작업에 적합하다. 2) Aiohttp aiohttp는 asyncio를 위한 http 서버/클라이언트 요청을 수행하는 라이브러리이다. 파이썬 request가 동기로 요청을 처리하기 때문에 비동기로 http 요청을 처리하기 위해서는..

python 메모

[python] ProcessPoolExecutor로 분할+병렬 연산

대용량 데이터를 처리할 때 여러개의 프로세스로 분할하여 처리하고 다시 합치고 싶은 경우들이 생각보다 빈번하다. 이때 concurrent.futures.ProcessPoolExecutor를 사용하면 매우 간단하게 처리할 수 있다. 매우 긴 배열을 process 개수만큼 잘라서 동일한 연산을 수행하고 최종 결과를 얻어오는 상황에서 사용할 수 있는 코드는 다음과 같다. 이는 배열 뿐만 아니라 pandas DataFrame 등에도 유용하게 사용할 수 있다. * ProcessPoolExecutor 병렬 연산 과정 배열을 process 개수로 나눠 chunk size 크기로 자른다.(메모리 효율성을 위해 인덱스만 저장) 배열에 적용할 함수를 정의한다. 함수를 병렬로 실행한다. 2번에서 주의할 점은 함수가 fork ..

python 메모

[pandas] 특정 row들의 셀 병합하여 excel로 읽고 쓰기

pandas는 모든 데이터를 테이블 형태로 다루는데 엑셀에서 보기 편하게 특정 row들을 하나의 셀로 병합하여 저장하고 읽을 때가 있다. 1. row 병합 후 인덱스로 설정 ris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv') not_merged = ris[['species']+ris.columns[:-1].tolist()].head() print(not_merged.to_markdown()) >>>> | | species | sepal_length | sepal_width | petal_length | petal_width | |---:|:----------|---------------:|--..

python 메모

[pandas] warning 메세지 출력 안하기

import warnings warnings.filterwarnings(action='ignore')

python 메모

[sklearn] classification_report 결과 파일로 저장하기

sklearn의 classification_report는 분류 결과값을 class별로 매우 잘 뽑아준다. from sklearn.metrics import classification_report y_true = [0, 1, 2, 2, 2] y_pred = [0, 0, 2, 2, 1] target_names = ['class 0', 'class 1', 'class 2'] print(classification_report(y_true, y_pred, target_names=target_names)) >>>> precision recall f1-score support class 0 0.50 1.00 0.67 1 class 1 0.00 0.00 0.00 1 class 2 1.00 0.67 0.80 3 accu..

python 메모

[python] eval() 내장함수

python 예약어 중 eval이라는 예약어가 있다(무엇에 쓰는 물건인고?). 무엇인지, 언제 쓰는지 알아보자. 1. eval() python3 문서에서는 eval()에 대해 다음과 같이 설명하고 있다. eval(expression[, globals[, locals]]) ... 인자는 '문자열 및 선택적 globals 및 locals'다. (...) 반환 값은 계산된 표현식의 결과입니다. 즉 문자열이나 표현식, 변수들을 입력으로 받아 이를 계산하고 반환해주는 함수이다. 단, 문자열, 표현식, 변수들이 모두 str 타입이어야 한다. 아래는 간단한 예제이다. x = 1 eval('x+1') >>>> 2 2. 문자열 입력 requests 등으로 json, list 등의 데이터를 받는 경우 문자열로 받아지는 경..

python 메모

[python] requests 라이브러리 한글 인코딩

⊙requests 라이브러리에서의 한글 깨짐 현상 한글의 경우 requests, 라이브러리를 통해 전달할 때, 특별히 주의해야 한다. 아래 예시처럼 json이 자동으로 ascii로 변환하기 때문에 입력이 깨져서 전달이 되기 때문이다. import json post_data = {"item": "한글 인코딩"} with open('sample.json', 'w') as f: json.dump(post_data, f) # sample.json 파일 열어보면 아래와 같이 저장되어 있음 {"item": "\ud55c\uae00 \uc778\ucf54\ub529"} 한글 데이터를 json.dump()로 저장하고 해당 파일을 열면 한글이 ascii 인코딩으로 저장이 된다. requests를 통해 데이터를 전달할 때..

python 메모

[pandas] apply + custom function을 사용한 다중 입력 및 출력

DataFrame에서 다중 입력을 받아 다중 출력을 계산하는 경우가 있으며, condition이 복잡한 경우 custom function을 만드는게 좋다. 다음과 같은 상황을 가정해보자. DataFrame의 multiple column을 활용하여 multiple output 계산 새로운 column을 만들어 해당 column을 원래 DataFrame 오른쪽에 append 이때 apply 함수에 result_type='expand' arguement을 사용하면 된다. 0. pandas apply + custom function 다중입출력 아래와 같은 DataFrame이 있을 때, 여러 개의 column을 입력으로 받아 여러개의 새로운 column을 만드는 함수를 적용하려고 한다. df = pd.DataFr..

python 메모

[python] datetime 사용하기

string 형태의 날짜를 datetime 데이터로 바꾸거나 vice-versa로 작업하는 경우를 위해 정리하고자 한다. (1) string → datetime string 데이터를 날짜 형식으로 바꾸기 위해서는 datetime 모듈의 strptime을 사용하면 편하다. 이때 중요한 것은 parsing하는 데이터 포맷을 알맞게 입력해줘야 한다(!) import datetime ## 올바른 포맷 string_data = '21/06/06' datetime.datetime.strptime(string_data, '%y/%d/%m') >>>> datetime.datetime(2021, 6, 6, 0, 0) ## 잘못된 포맷 string_data = '20210606' datetime.datetime.strpt..