首页 > 解决方案 > Pandas 1.0 从年份和日期创建月份列

问题描述

我有一个数据框df,其值为:

df.iloc[1:4, 7:9]
    Year  Month
38  2020      4
65  2021      4
92  2022      4

我正在尝试创建一个新MonthIdx列:

df['MonthIdx'] = pd.to_timedelta(df['Year'], unit='Y') + pd.to_timedelta(df['Month'], unit='M') + pd.to_timedelta(1, unit='D')

但我得到了错误:

ValueError: Units 'M' and 'Y' are no longer supported, as they do not represent unambiguous timedelta values durations.

以下是所需的输出:

df['MonthIdx']
    MonthIdx
38  2020/04/01
65  2021/04/01
92  2022/04/01

标签: python-3.8pandas-1.0

解决方案


因此,您可以在系列中填充月份值,然后重新格式化以获得所有值的日期时间:

month = df.Month.astype(str).str.pad(width=2, side='left', fillchar='0')
df['MonthIdx'] = pd.to_datetime(pd.Series([int('%d%s' % (x,y)) for x,y in zip(df['Year'],month)]),format='%Y%m')

这会给你:

   Year  Month   MonthIdx
0  2020      4 2020-04-01
1  2021      4 2021-04-01
2  2022      4 2022-04-01

您可以将日期重新格式化为字符串以完全匹配您的格式:

df['MonthIdx'] = df['MonthIdx'].apply(lambda x: x.strftime('%Y/%m/%d'))

给你:

   Year  Month    MonthIdx
0  2020      4  2020/04/01
1  2021      4  2021/04/01
2  2022      4  2022/04/01

推荐阅读