Pandas resample函数报错TypeError: Only valid with DatetimeIndex
1、现象
从MySQL数据库中读入数据到DataFrame中,使用resample函数,报错:
week_df = df.resample("W").first()
按周取样报错:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of ‘Index’
检查数据类型:<class ‘datetime.date’>
print(type(df.index[0]))
<class 'datetime.date'>
做了一个测试程序,resample函数运行正常。
import pandas as pd
import numpy as np
dayseries = pd.date_range('1/1/2022',periods=30,freq='D')
ts1 = pd.Series(np.random.randn(len(dayseries)),index=dayseries)
ts2 = pd.Series(np.random.randn(len(dayseries)),index=dayseries)
ts3 = pd.Series(np.random.randn(len(dayseries)),index=dayseries)
ts4 = pd.Series(np.random.randn(len(dayseries)),index=dayseries)
ts5 = pd.Series(np.random.randn(len(dayseries)),index=dayseries)
df = pd.DataFrame({'open':ts1,'high':ts2,'low':ts3,'close':ts4, 'volume':ts5} ,index = dayseries)
df.index.name='dayseries'
#用于产生聚合值的函数名或数组函数,例如‘mean’、‘ohlc’、np.max等,默认是‘mean’,
#其他常用的值由:‘first’、‘last’、‘median’、‘max’、‘min’
df_week = pd.DataFrame({'open':df['open'].resample('W').first(),
'close':df['close'].resample('W').last(),
'high':df['high'].resample('W').max(),
'low':df['low'].resample('W').min(),
'volume':df['volume'].resample('W').sum()})
#df['open'].resample('W').first()
print(type(df_week.index[0])) # <class 'pandas._libs.tslibs.timestamps.Timestamp'>
df_week
必须通过索引进行取样,索引数据类型是时间戳:
print(type(df_week.index[0]))
<class 'pandas._libs.tslibs.timestamps.Timestamp'>
2、原因
原因:通过测试,可以看到是resample必须使用时间戳的数据类型,否则提示数据类型不对。
解决方法:直接转换索引的数据类型即可 。
开始想调整数据库字段的数据类型,匹配dataframe的时间戳,走了弯路。
df.index = pd.to_datetime(df.index)
print(type(df.index[0]))
索引的数据类型是,<class ‘pandas._libs.tslibs.timestamps.Timestamp’>