【问题标题】:Pandas Time Series Resampling: KeyError: "['year' 'month' 'day'] not in index"Pandas 时间序列重采样:KeyError:“['year''month''day'] 不在索引中”
【发布时间】:2017-07-29 20:11:29
【问题描述】:

请帮忙

我尝试重新采样数据,但没有成功。它会生成上述错误,当应用 DatetimeIndex 它会截断时间戳,删除 HH:MM:SS。它仍然无法将数据识别为 Datetime 对象。提前致谢。

源文件可以在here找到

import pandas as pd
import numpy as np

df= pd.read_csv('20170713.csv')
df2= df.loc[:,['sen_id', 'pos_id', 'heat_val', 'sat_val', 'timestamp']] 
cols = df2.columns.tolist() 
cols = cols[-1:] + cols[:-1]
df2 = df2[cols]
#print(df2.head())

df3 = df2.set_index(['timestamp'])
df3.index = pd.DatetimeIndex(df3.index)
print(df3.head())

pd.to_datetime(df3[['year', 'month', 'day']])
df3.resample('1H').mean()
print(df3)

【问题讨论】:

  • 所以您希望索引是 yyyy-mm-dd 的日期时间?你能提供一个你希望最终输出的样本吗?
  • 感谢您的回答!非常喜欢:-)

标签: python python-3.x pandas time-series


【解决方案1】:

问题在于pd.to_datetime() 的使用不正确,您将df3 中不存在的三列提供为df3[['year','month','day']]。相反,您只想提供series。然后你想提供参数format='%d/%m/%Y %H:%M',它对应于你的日期strptime格式

df= pd.read_csv('20170713.csv')
df2= df.loc[:,['sen_id', 'pos_id', 'heat_val', 'sat_val', 'timestamp']] 
cols = df2.columns.tolist() 
cols = cols[-1:] + cols[:-1]
df2 = df2[cols]
#print(df2.head())

df3 = df2.set_index(['timestamp'])
#df3.index = pd.DatetimeIndex(df3.index)
#print(df3.head())

#pd.to_datetime(df3[['year', 'month', 'day']])
df3.index = pd.to_datetime(df3.index,format='%d/%m/%Y %H:%M')
df3 = df3.resample('1H').mean()
print(df3)

例如,为了可读性,您的代码实际上也可以压缩,

df = pd.read_csv('20170713.csv')

#Preserve desired columns and reorder as df2
df2 = df[['timestamp', 'sen_id', 'pos_id', 'heat_val', 'sat_val']]

#set timestamp as index and convert to datetime
df2.set_index(['timestamp'],drop=True,inplace=True)
df2.index = pd.to_datetime(df2.index,format='%d/%m/%Y %H:%M')

#resample
df3 = df2.resample('1H').mean()

print df3

【讨论】:

  • 非常感谢,您的压缩代码更快。保持良好的工作。 pd.to_datetime 的使用有点令人困惑。非常感谢!太爱了!
  • 没问题!也很高兴帮助
猜你喜欢
  • 1970-01-01
  • 2012-03-17
  • 1970-01-01
  • 1970-01-01
  • 2018-12-18
  • 2018-08-17
  • 1970-01-01
  • 2014-07-24
  • 2021-12-12
相关资源
最近更新 更多