从两列创建日期对象

2024-04-19 21:13:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两列:

dt_year, dt_month
2014     3

我需要一个日期栏

我试过这样的方法:

pd.to_datetime((df.dt_year + df.dt_month +1).apply(str),format='%Y%m%d')

但我有个错误:

ValueError: time data '2014' does not match format '%Y%m%d' (match)

有什么想法吗


Tags: to方法formatdfdatetimetimematch错误
1条回答
网友
1楼 · 发布于 2024-04-19 21:13:50

首先,将列名更改为更普通的名称。然后添加'day'

df.columns = df.columns.str.replace('dt_', '')
df['day'] = 1

df

   year  month  day
0  2014      3    1

然后奇迹发生了

pd.to_datetime(df)

0   2014-03-01
dtype: datetime64[ns]

相关问题 更多 >