Pandas resample函数报错TypeError: Only valid with DatetimeIndex

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’>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值