python - 如何将年、月和日列合并为单个日期时间列?

标签 python pandas date datetime timestamp

我有以下数据框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/

相关文章:

python - 作为函数参数的 Pandas DataFrame - Python

date - 在开始日期和结束日期之间查询 CouchDB 文档

javascript - jquery datepicker 删除当前日期高亮类

python - scipy.optimize 使用 python 解决以下等式

python - 不断检查列表并在列表中有项目时执行某些操作

python - 嵌套字典理解 : Too many values to unpack

python - 使用plot_date绘制日期

python - 对于不可行的 NLP,Scipy.optimize 成功终止

python - 使用 pandas 将顺序数据文件重新格式化为数据框

python - 删除行索引数据框 Pandas