合并Pandas DataFrame DateTime列 [英] Combine Pandas DataFrame DateTime Columns

查看:204
本文介绍了合并Pandas DataFrame DateTime列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大概我有如下数据框:

Year Month Day
2003 1     8
2003 2     7

如何在数据框中新定义的列中组合年,月和日,因此该数据框将是:

How to combine the Year, Month, and Day in the newly defined column in the dataframe as such the dataframe would be:

Year Month Day Date
2003 1     8   2003-1-8
2003 2     7   2003-2-7

对此有任何想法吗?

我正在使用熊猫python数据框

I am using pandas python dataframe

谢谢!

推荐答案

>>> from datetime import datetime
>>> df['Date'] = df.apply(lambda row: datetime(
                              row['Year'], row['Month'], row['Day']), axis=1)
>>> df
   Year  Month  Day                Date
0  2003      1    8 2003-01-08 00:00:00
1  2003      2    7 2003-02-07 00:00:00

更新2020-03-12:来自sacul的答案更好,更快:

Update 2020-03-12: The answer from sacul is better and faster:

%%timeit
df.apply(lambda row: datetime(
                              row['Year'], row['Month'], row['Day']), axis=1)

2.53 s ± 169 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# use below, above is slow!!!
%%timeit
pd.to_datetime(df[['Year','Month','Day']])

14.4 ms ± 3.37 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

这篇关于合并Pandas DataFrame DateTime列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆