# n주차 만들기
from datetime import datetime, timedelta
def get_date(y, m, d):
s = f'{y:04d}-{m:02d}-{d:02d}'
return datetime.strptime(s, '%Y-%m-%d')
def get_week_no(y, m, d):
target = get_date(y, m, d)
firstday = target.replace(day=1)
if firstday.weekday() == 6:
origin = firstday
elif firstday.weekday() < 3:
origin = firstday - timedelta(days=firstday.weekday() + 1)
else:
origin = firstday + timedelta(days=6-firstday.weekday())
return (target - origin).days // 7 + 1
def week(df):
a = []
for i in df['date'].values:
yi = int(i[:4])
mi = int(i[5:7])
di = int(i[8:])
a.append(get_week_no(yi, mi, di))
df['week'] = a
return df
def change_week(df):
df = week(df)
df['date1'] = df['date'].str[:7]
t = df[df['week']==0]
t = t.drop_duplicates(['date1'])
df.loc[df["date1"].isin(t["date1"]), "week"] = df.loc[df["date1"].isin(t["date1"]), "week"] + 1
return df
train = change_week(train)
test = change_week(test)
train