日付の加工

投稿者: | 2021-12-26

目次

サンプル作成

sample = {'date':['2021-12-26', '2022-03-27', '2022-04-15', '2023-03-10',]}
df = pd.DataFrame(sample)
print(df.dtypes)
df

DatetimeIndexに変換

df['date'] = pd.DatetimeIndex(df['date'])

年、月を追加

# 列year,monthを追加
df['year'] = pd.DatetimeIndex(df['date']).year
df['month'] = pd.DatetimeIndex(df['date']).month
df

年度を追加

# 年度用の列を作成
df['fiscal_year'] = pd.DatetimeIndex(df['date']).year

# 任意の位置を(取得)変更する「loc(行ラベル、列ラベル)」を利用して
# 「行:'month'<4、列:'fiscal_year'」を満たすセルに-1した年を代入している
df.loc[df['month'] < 4, 'fiscal_year'] -= 1