我有2栏:
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)
有任何想法吗?
最佳答案
首先,将列名更改为更普通的名称。然后添加'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]
关于python - 从2列创建日期对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41293424/