我有以下数据框df
:
id lat lon year month day
0 381 53.30660 -0.54649 2004 1 2
1 381 53.30660 -0.54649 2004 1 3
2 381 53.30660 -0.54649 2004 1 4
我想创建一个新列df['Date']
,其中年
、月
和日
列按照 yyyy-m-d
格式组合。
已关注 this post ,我做了:
`df['Date']=pd.to_datetime(df['year']*10000000000
+df['month']*100000000
+df['day']*1000000,
format='%Y-%m-%d%')`
结果不是我所期望的,因为它从 1970 年开始,而不是 2004 年,而且它还包含我没有指定的小时标记:
id lat lon year month day Date
0 381 53.30660 -0.54649 2004 1 2 1970-01-01 05:34:00.102
1 381 53.30660 -0.54649 2004 1 3 1970-01-01 05:34:00.103
2 381 53.30660 -0.54649 2004 1 4 1970-01-01 05:34:00.104
由于日期应采用 2004-1-2
格式,我做错了什么?
最佳答案
有一个更简单的方法:
In [250]: df['Date']=pd.to_datetime(df[['year','month','day']])
In [251]: df
Out[251]:
id lat lon year month day Date
0 381 53.3066 -0.54649 2004 1 2 2004-01-02
1 381 53.3066 -0.54649 2004 1 3 2004-01-03
2 381 53.3066 -0.54649 2004 1 4 2004-01-04
来自 docs :
Assembling a datetime from multiple columns of a DataFrame. The keys can be common abbreviations like [
year
,month
,day
,minute
,second
,ms
,us
,ns
]) or plurals of the same
关于python - 如何将年、月和日列合并为单个日期时间列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48155787/