组合列以在熊猫中创建datetimeindex

时间:2020-03-30 06:16:31

标签: python pandas datetimeindex

我想将日期和时间数据合并到Pandas Dataframe的多个列中以创建DatetimeIndex。我有这个:

In:  
import pandas as pd
df = pd.DataFrame({'the_date':['2020-03-26', '2020-03-26', '2020-03-25','2020-03-25'],
                   'hour': [1,2,1,2],
                   'data': [4,5,6,7]})
df

Out:    
the_date    hour    data
0   2020-03-26  1   4
1   2020-03-26  2   5
2   2020-03-25  1   6
3   2020-03-25  2   7


df['ts'] = df.apply(lambda row: pd.to_datetime(row['the_date'] + " " + str(row['hour']) +":00:00"))
df = df.set_index('ts')

但是我遇到了这个错误:

KeyError: ('the_date', 'occurred at index the_date') 我在做什么错了?

2 个答案:

答案 0 :(得分:1)

您可以通过to_timedelta避免循环(应用在幕后的循环):

df['the_date'] = pd.to_timedelta(df['hour'], unit='H') + pd.to_datetime(df['the_date'])  

答案 1 :(得分:1)

实际上,这是一个很常见的错误!

pandas.DataFrame.apply的默认轴为0,即lambda函数应用于每列(因此,您不能在计算时考虑其他列的值)。您想要将轴更改为1,即将其应用于每行:

df['ts'] = df.apply(lambda row: pd.to_datetime(row['the_date'] + " " + str(row['hour']) +":00:00"), axis=1)