python3.5 / pandas - 将多个列转换为datetime

时间:2016-07-07 02:36:14

标签: python datetime pandas

所以我试图将2列转换为1个datetime列。输入列如下所示:

date            hour
1/1/2015          1
1/1/2015          2
1/1/2015          3

其中df.date的值为stringdf.hour的值为int。我试图将这两个列转换成一个这样的:

datetime
2015-1-1 1:00:00
2015-1-1 2:00:00
2015-1-1 3:00:00

我认为一个简单的df['x'] = pd.to_datetime(df[['date', 'hour']]会起作用,但我会得到一个ValueError

3 个答案:

答案 0 :(得分:2)

您可以将两列作为单个列粘贴在一起,然后使用相应的format参数进行转换:

pd.to_datetime(df['date'] + ' ' + df['hour'].astype(str), format = "%d/%m/%Y %H")

# 0   2015-01-01 01:00:00
# 1   2015-01-01 02:00:00
# 2   2015-01-01 03:00:00
# dtype: datetime64[ns]

答案 1 :(得分:2)

基本上,您需要使用pandas.to_datetimedatetime.timedelta

from datetime import timedelta
df = pd.to_datetime(df['date']) + df['hour'].apply(lambda x: timedelta(hours=int(x)))

说明:

from datetime import timedelta
dft['date'] = pd.to_datetime(dft['date'])
dft['hour_h'] = dft['hour'].apply(lambda x: timedelta(hours=int(x)))
dff = dft['date']+dft['hour_h']

<强>输出:

dff
Out[42]: 
0   2015-01-01 01:00:00
1   2015-01-01 02:00:00
2   2015-01-01 03:00:00
dtype: datetime64[ns]

答案 2 :(得分:1)

这是另一种方法:

In [224]:
df['datetime'] = pd.to_datetime(df['date']) + pd.TimedeltaIndex(df['hour'], unit='h')
df

Out[224]:
       date  hour            datetime
0  1/1/2015     1 2015-01-01 01:00:00
1  1/1/2015     2 2015-01-01 02:00:00
2  1/1/2015     3 2015-01-01 03:00:00

这里的关键区别主要是从小时列构建TimedeltaIndex并将其添加到datetime

转换后的to_datetime col结果中