我想将日期和时间数据合并到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')
我在做什么错了?
答案 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)