9

假设我有如下数据框:

Year Month Day
2003 1     8
2003 2     7

如何在数据框中新定义的列中组合年、月和日,这样数据框将是:

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

对此有任何想法吗?

我正在使用熊猫 python 数据框

谢谢!

4

2 回答 2

17
>>> 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的答案更好更快:

%%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)
于 2013-09-22T14:51:25.867 回答
2

更好的使用pd.to_datetime

df['Date'] = pd.to_datetime(df[['Year','Month','Day']])
>>> df
   Year  Month  Day       Date
0  2003      1    8 2003-01-08
1  2003      2    7 2003-02-07
于 2018-12-04T01:55:33.917 回答