23년 2월의 공부 - datetime(날짜와 시간 다루기), pandas display options, 모델 이름 추출, directory 생성
포스트
취소

23년 2월의 공부 - datetime(날짜와 시간 다루기), pandas display options, 모델 이름 추출, directory 생성

2023년 2월 동안 검색하고 공부한 것들을 정리한 내용입니다.

1. datetime

datetime은 날짜와 시간을 다루는 파이썬의 기본 패키지입니다. 그 중 주로 사용하는 몇 가지 함수를 소개합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from datetime import datetime
import datetime as dt

now = datetime.now()
now
# datetime.datetime(2023, 2, 18, 5, 42, 52, 830805)

# strftime: datetime -> 문자열
str_date = datetime.strftime(now, "%Y%m%d")
str_date
# '20230218'

# strptime: 문자열 -> datetime
datetime.strptime(str_date, "%Y%m%d")
# datetime.datetime(2023, 2, 18, 0, 0)

# timedelta: 날짜 및 시간 연산
now + dt.timedelta(days=1)
# datetime.datetime(2023, 2, 19, 5, 42, 52, 830805)

# 요일
# 0: 월요일, 6: 일요일
now.weekday()
# 5

datetime 이외에도 날짜와 시간을 다루는 파이썬 패키지는 pendulum이 있으며, 공식문서나 이전 글을 참고하시면 됩니다.

2. pandas options - 행, 열 등 최대 표시 수 변경

pandas에서 현재 설정된 option을 보는 경우는 2가지 방법이 있습니다. 하나는 get_option() 함수를 통해 불러오는 방법과 다른 방법은 options에서 해당 옵션을 확인하는 방법입니다. 실제 사용하는 방법은 아래와 같습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
import pandas as pd

# 방법1
print(pd.get_option('display.max_rows'))
print(pd.get_option('display.max_columns'))
# 60
# 20

# 방법2
print(pd.options.display.max_rows)
print(pd.options.display.max_columns)
# 60
# 20

옵션을 변경하고자 할 때도 위의 방법이 비슷하게 사용됩니다.

1
2
3
4
5
6
7
pd.set_option('display.max_rows', 50)
print(pd.get_option('display.max_rows'))
# 50

pd.options.display.max_columns = 30
print(pd.options.display.max_columns)
# 30

‘max_rows’와 ‘max_columns’ 이외에 자주 사용하는 옵션은 ‘max_colwidth’로, 데이터가 길이가 긴 text여서 뒤의 값이 잘리는 경우에 해당 옵션을 조절하여 값을 확인할 수 있습니다.

3. 사용한 모델 이름 추출하기

여러 개의 모델을 이용할 때, 사용한 모델이 어떤 모델인지에 대한 정보가 필요할 수 있습니다. 이에 대한 코드는 아래와 같습니다.

1
2
3
4
5
6
7
8
9
10
11
from sklearn.ensemble import RandomForestClassifier
from lightgbm import LGBMClassifier
from xgboost import XGBClassifier

model1 = RandomForestClassifier()
model2 = LGBMClassifier()
model3 = XGBClassifier()

print(type(model1).__name__) # 'RandomForestClassifier'
print(type(model2).__name__) # 'LGBMClassifier'
print(type(model3).__name__) # 'XGBClassifier'

4. 폴더 생성하기

파일을 저장할 폴더를 생성하기 위한 함수입니다. exist_ok=False 인 경우에는 FileExistError가 출력됩니다.

1
2
3
4
import os

dir_path = 'path_of_directory'
os.makedirs(dir_path, exist_ok=True) 
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.