python pandas合并,使用python 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

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

解决方案

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]

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值