使用python pandas合并日期和时间列 [英] Combine Date and Time columns using python pandas
问题描述
我有一个带有以下几栏的pandas数据框;
I have a pandas dataframe with the following columns;
Date Time
01-06-2013 23:00:00
02-06-2013 01:00:00
02-06-2013 21:00:00
02-06-2013 22:00:00
02-06-2013 23:00:00
03-06-2013 01:00:00
03-06-2013 21:00:00
03-06-2013 22:00:00
03-06-2013 23:00:00
04-06-2013 01:00:00
如何合并数据['Date']& data ['Time']得到以下内容?有没有办法使用pd.to_datetime
做到这一点?
How do I combine data['Date'] & data['Time'] to get the following? Is there a way of doing it using pd.to_datetime
?
Date
01-06-2013 23:00:00
02-06-2013 01:00:00
02-06-2013 21:00:00
02-06-2013 22:00:00
02-06-2013 23:00:00
03-06-2013 01:00:00
03-06-2013 21:00:00
03-06-2013 22:00:00
03-06-2013 23:00:00
04-06-2013 01:00:00
推荐答案
值得一提的是,您可能已经能够直接在 中阅读此内容,例如如果您使用的是 read_csv
使用parse_dates=[['Date', 'Time']]
.
It's worth mentioning that you may have been able to read this in directly e.g. if you were using read_csv
using parse_dates=[['Date', 'Time']]
.
假设这些只是字符串,您可以简单地将它们添加在一起(带有空格),从而允许您应用
Assuming these are just strings you could simply add them together (with a space), allowing you to apply to_datetime
:
In [11]: df['Date'] + ' ' + df['Time']
Out[11]:
0 01-06-2013 23:00:00
1 02-06-2013 01:00:00
2 02-06-2013 21:00:00
3 02-06-2013 22:00:00
4 02-06-2013 23:00:00
5 03-06-2013 01:00:00
6 03-06-2013 21:00:00
7 03-06-2013 22:00:00
8 03-06-2013 23:00:00
9 04-06-2013 01:00:00
dtype: object
In [12]: pd.to_datetime(df['Date'] + ' ' + df['Time'])
Out[12]:
0 2013-01-06 23:00:00
1 2013-02-06 01:00:00
2 2013-02-06 21:00:00
3 2013-02-06 22:00:00
4 2013-02-06 23:00:00
5 2013-03-06 01:00:00
6 2013-03-06 21:00:00
7 2013-03-06 22:00:00
8 2013-03-06 23:00:00
9 2013-04-06 01:00:00
dtype: datetime64[ns]
注意:令人惊讶的是(对我而言),这适用于将NaN转换为NaT的情况,但值得担心的是转换(也许使用raise
参数).
Note: surprisingly (for me), this works fine with NaNs being converted to NaT, but it is worth worrying that the conversion (perhaps using the raise
argument).
这篇关于使用python pandas合并日期和时间列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!