请帮忙
我曾尝试重新采样数据,但没有成功。它会生成上述错误,当应用 DatetimeIndex 时,它会截断时间戳,删除 HH:MM:SS。它仍然无法将数据识别为 Datetime 对象。提前致谢。
源文件可以在这里找到
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)
问题是 的使用不正确pd.to_datetime()
,您提供了三个在df3
as 中不存在的列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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句