我有一个数据框,其中只有年份和月份的分隔列,例如:
Year Month
2001 1
2001 2
2001 3
.
.
2010 1
2010 2
.
使用 pd.to_datetime(df[['year', 'month']])
转换为 pd.datetime
需要几天来匹配格式,所以我得到错误:
ValueError:组装映射至少需要指定[年、月、日]:缺少[日]
我觉得我可以重复填写一个新列,其中 Day = 1 重复,但我想避免这种情况,因为我只想按年-月创建一个时间序列。
有没有办法将年月映射到日期以正确绘制图表?
最佳答案
不存在只有一个月的日期时间
之类的事情。
pd.to_datetime
assign
使用参数中指定的列创建 df
的副本。
如@timgeb声明:
Explanation:
df.assign(day=1)
is a quick way to create a temporary dataframe with a'day'
column without having to modify your original dataframe.
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
关于python - 将数据帧年份和月份合并到新对象Python中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53271332/