合并列以在 pandas 中创建日期时间索引

Combining columns to create datetimeindex in pandas

我想合并 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') 我做错了什么?

您可以通过 to_timedelta:

避免循环(apply 是引擎盖下的循环)
df['the_date'] = pd.to_timedelta(df['hour'], unit='H') + pd.to_datetime(df['the_date'])  

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

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)