2023년 3월 동안 검색하고 공부한 것들을 정리한 내용입니다.
Summary
np.logical_or()
: 2개의 array에 대한 논리합 계산.itertools.product()
: iterable 객체의 cartesian product 계산, 2개 이상의 iterable 객체 가능.pd.offsets.MonthBegin(n)
: timestamp에 대해 n개월 계산 가능.
1. np.logical_or
- 참고자료
np.logical_or
은 2개의 array에 대한 논리합을 계산하는 함수입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
df = load_iris()
X = df.data
y = df.target
iris_cols = ["_".join(feature_nm.split(" ")[:2]) for feature_nm in df.feature_names] + ['target']
print(X.shape, y.shape)
# (150, 4) (150,)
iris_df = pd.DataFrame(np.hstack((X,y.reshape(-1, 1))), columns = iris_cols)
iris_dict = dict()
for key, item in zip(np.arange(0,3), df.target_names):
iris_dict[key] = item
iris_dict
# {0: 'setosa', 1: 'versicolor', 2: 'virginica'}
iris_df['target'] = iris_df['target'].map(iris_dict)
1
2
3
4
5
6
7
8
9
10
11
12
13
cond1 = iris_df.columns.str.startswith('sepal')
cond1
# array([ True, True, False, False, False])
cond2 = iris_df.columns.str.startswith('petal')
cond2
# array([False, False, True, True, False])
np.logical_or(cond1, cond2)
# array([ True, True, True, True, False])
cond1 + cond2
# array([ True, True, True, True, False])
2. list의 가능한 조합 구하기
product()
는 iterable한 입력에 대한 cartesian product를 구하는 함수입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from itertools import product
a = ['A', 'B']
b = 'ab'
c = [1,2]
list(product(a,b,c))
# [('A', 'a', 1),
# ('A', 'a', 2),
# ('A', 'b', 1),
# ('A', 'b', 2),
# ('B', 'a', 1),
# ('B', 'a', 2),
# ('B', 'b', 1),
# ('B', 'b', 2)]
참고로, itertools.permutations()
와 itertools.combinations()
함수를 통해 iterable한 하나의 입력에 대한 조합 또는 순열을 계산할 수 있습니다.
3. pd.offsets.MonthBegin
pd.offsets.MonthBegin(n)
함수를 이용하면 timestamp에 대해 n개월 이동한 월의 시작일을 구할 수 있습니다. datetime.timedelta()
함수에서 지정할 수 있는 최대 시간 단위가 ‘일’(days)이기 때문에 ‘월’(month)에 대한 계산을 할 때 사용할 수 있습니다. 동일한 기능을 하는 다른 함수로는 dateutil.relativedelta.relativedelta()
도 사용 가능합니다. 또한, 해당 월초가 아닌 월말을 계산하려고 하면 pd.offsets.MonthEnd()
함수를 이용할 수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import pandas as pd
from datetime import datetime
import datetime as dt
dt_r = pd.date_range(start = '2020-01-01', end = '2023-03-01', freq='1D', tz='Asia/Seoul')
dt_r
# DatetimeIndex(['2020-01-01 00:00:00+09:00', '2020-01-02 00:00:00+09:00',
# '2020-01-03 00:00:00+09:00', '2020-01-04 00:00:00+09:00',
# '2020-01-05 00:00:00+09:00', '2020-01-06 00:00:00+09:00',
# '2020-01-07 00:00:00+09:00', '2020-01-08 00:00:00+09:00',
# '2020-01-09 00:00:00+09:00', '2020-01-10 00:00:00+09:00',
# ...
# '2023-02-20 00:00:00+09:00', '2023-02-21 00:00:00+09:00',
# '2023-02-22 00:00:00+09:00', '2023-02-23 00:00:00+09:00',
# '2023-02-24 00:00:00+09:00', '2023-02-25 00:00:00+09:00',
# '2023-02-26 00:00:00+09:00', '2023-02-27 00:00:00+09:00',
# '2023-02-28 00:00:00+09:00', '2023-03-01 00:00:00+09:00'],
# dtype='datetime64[ns, Asia/Seoul]', length=1156, freq='D')
dt_r[0] - pd.offsets.MonthBegin(n=1)
# Timestamp('2019-12-01 00:00:00+0900', tz='Asia/Seoul', freq='D')
dt_r[0] - dt.timedelta(days=31)
# Timestamp('2019-12-01 00:00:00+0900', tz='Asia/Seoul', freq='D')
dt_r[0] - pd.offsets.MonthEnd(n=1)
# Timestamp('2019-12-31 00:00:00+0900', tz='Asia/Seoul', freq='D')