这个方法也有效;
df['combined'] = pd.to_datetime([f'{y}-{m}-{d}' for y, m, d in zip(df.year, df.month, df.day)])
编辑 2019-11-17 回复@HenryHenrinson
感谢您的 cmets。我确实回去检查性能,看看你是否正确。
我创建了一个从 1980 年 1 月 1 日到 2019 年 1 月 1 日的数据框。
df.head()
year month day
0 1980 1 1
1 1980 1 2
2 1980 1 3
3 1980 1 4
4 1980 1 5
print(df.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 14246 entries, 0 to 14245
Data columns (total 3 columns):
year 14246 non-null int64
month 14246 non-null int64
day 14246 non-null int64
dtypes: int64(3)
memory usage: 334.0 KB
None
测试下面的 iterrows 解决方案:
%timeit [datetime.date(year=x[1].year, month=x[1].month, day=x[1].day) for x in df.iterrows()]
results in:
1.23 s ± 30.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
测试我的解决方案:
%timeit pd.Series(pd.to_datetime([f'{y}-{m}-{d}' for y, m, d in zip(df.year, df.month, df.day)]))
results in:
9.9 ms ± 159 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
并测试伟大而强大的@wenyoben 的解决方案...
%timeit pd.to_datetime(df)
results in:
8.81 ms ± 206 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
@wenyoben 解决方案最快、最优雅,应该是首选答案。