首页 > 解决方案 > 将数据框年份和月份组合到新对象Python中

问题描述

我有一个数据框,其中只有年和月的单独列,例如:

Year        Month
2001        1
2001        2
2001        3
.
.
2010        1
2010        2
.

转换为pd.datetimeusingpd.to_datetime(df[['year', 'month']])需要几天才能匹配格式,所以我收到错误:

ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day] is missing

我觉得我可以用 Day = 1 重复填充一个新列,但我想避免这种情况,因为我只想按年创建一个时间序列。

有没有办法将年月映射到日期以正确绘制图表?

标签: pythonpython-3.xpandasdatedataframe

解决方案


没有只有一个月的事情datetime

pd.to_datetime

assigndf使用 arguments` 中指定的列创建副本。

正如@timgeb所说:

说明:是一种无需修改原始数据框df.assign(day=1)即可创建带有列的临时数据框的快速方法。'day'

pd.to_datetime(df.assign(day=1))

0   2001-01-01
1   2001-02-01
2   2001-03-01
3   2010-01-01
4   2010-02-01
dtype: datetime64[ns]

to_period

您可能想要使用to_period.

pd.to_datetime(df.assign(day=1)).dt.to_period('M')

0   2001-01
1   2001-02
2   2001-03
3   2010-01
4   2010-02
dtype: object

推荐阅读