1. 불규칙한 석유화학 가격 데이터 결측치를 채우기 위한 고민 끝에 방법이 나왔다.
물론, 불규칙하다고는 하지만 그 안의 몇 가지 규칙이 있기 때문에 그다지 복잡하지는 않다.
isocalendar가 반환하는 튜플값을 이용해서 연도값을 정하고 몇 가지 조건으로 결측치를 채운다.
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
28
29
30
31
32
33
34
|
df= pd.read_excel('C:\\pytest\\hpde.xlsx')
df['Date'].dt.date
df['Month'] = df['Date'].map(lambda x: x.month)
df['Year'] = df['Date'].map(lambda x: x.isocalendar()[0])
df['Date'] = df['Date'].dt.date
df['Week'] = df['Date'].map(lambda x: x.isocalendar()[1])
df.reset_index(drop = True).copy()
# 데이터 딕셔너리를 만드는 이유는 각 연도별 데이터 갯수와 시작주와 마지막 주를 확인하기 위함
Data_Org = {}
for Year in sorted(set(df["Year"])):
all_data = []
Data_Org[Year] = df[df["Year"].isin([Year])].reset_index(drop = True)
all_data.append(Data_Org[Year])
for Year in sorted(set(df["Year"])):
first_week = Data_Org[Year]['Week'].loc[0]
last_week_check = Data_Org[Year]['Week'].iloc[-2]
last_week = Data_Org[Year]['Week'].iloc[-1]
week_len = Data_Org[Year].shape[0]
print('{}년 : {}개, {}, {}, {}'.format(Year, week_len, first_week, last_week_check, last_week ))
table = df.pivot_table(values = 'Data', index = 'Year', columns='Week')
# 주별로 피벗을 하기 때문에 월 문제가 발생해도 상관없다.
for Year in sorted(set(df["Year"]))[1:]:
for i in table.columns.tolist():
if pd.isnull(table.loc[Year][1]) == True:
table.loc[Year][1] = table.loc[Year][2].copy()
elif pd.isnull(table.loc[Year][51]) == True:
table.loc[Year][51] = table.loc[Year][50].copy()
elif pd.isnull(table.loc[Year][52]) == True:
table.loc[Year][52] = table.loc[Year][51].copy()
|
cs |
여전히 간단하지만 쉽지 않았던 작업.
2. for Year in sorted(set(df["Year"])): 이하의 코드를 돌려보면
위와 같은 데이터 갯수 확인이 가능하다.