pandas處理數(shù)據(jù)的時(shí)候,可能會(huì)遇到分組問(wèn)題,比如說(shuō)一組統(tǒng)計(jì)數(shù)據(jù)需要按周分組統(tǒng)計(jì),這時(shí)候利用DataFrame中的resample函數(shù)就會(huì)非常方便與優(yōu)雅。
本文簡(jiǎn)單介紹resample函數(shù)的一些入門使用方法,方便后來(lái)者參考~
官方幫助文檔
resample函數(shù)的官方介紹可參考https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html
實(shí)例說(shuō)明

# 導(dǎo)入上圖中的數(shù)據(jù)
>>> df = pd.read_excel(r'resample_data.xlsx')
# 以一周內(nèi)第一天最為一條記錄
>>> df.resample("W", on="date").first()
date open high weekday
date
2022-04-17 2022-04-11 9620.50 9644.11 0
2022-04-24 2022-04-18 9473.89 9508.39 0
2022-05-01 2022-04-25 8707.82 8728.92 0
2022-05-08 2022-05-05 8720.32 8883.65 3
2022-05-15 2022-05-09 8761.02 8851.00 0
2022-05-22 2022-05-16 9159.94 9172.02 0
2022-05-29 2022-05-23 8985.73 9005.87 0
# 以一周內(nèi)最后一天最為一條記錄
>>> df.resample("W", on="date").last()
date open high weekday
date
2022-04-17 2022-04-15 9460.91 9643.38 4
2022-04-24 2022-04-22 8839.38 8920.13 4
2022-05-01 2022-04-29 8461.67 8750.18 4
2022-05-08 2022-05-06 8650.90 8838.78 4
2022-05-15 2022-05-13 9158.55 9211.67 4
2022-05-22 2022-05-20 8825.58 8976.35 4
2022-05-29 2022-05-25 8572.11 8693.04 2
# 分組聚合,open列取第一天的值,high列取一周內(nèi)最大值
>>> df.resample("W", on="date").agg({'open':'first', 'high':'max'})
open high
date
2022-04-17 9620.50 9694.81
2022-04-24 9473.89 9508.39
2022-05-01 8707.82 8750.18
2022-05-08 8720.32 8883.65
2022-05-15 8761.02 9211.67
2022-05-22 9159.94 9172.02
2022-05-29 8985.73 9005.87
# 分組聚合,自定義聚合函數(shù)
df.resample("W", on="date").agg({'open':'first', 'high': lambda x: max(x) + 2})
open high
date
2022-04-17 9620.50 9696.81
2022-04-24 9473.89 9510.39
2022-05-01 8707.82 8752.18
2022-05-08 8720.32 8885.65
2022-05-15 8761.02 9213.67
2022-05-22 9159.94 9174.02
2022-05-29 8985.73 9007.87
遇到的問(wèn)題
TypeError: Only valid with DatetimeIndex, Timedelta,but got an instance of 'Index'
該錯(cuò)誤是resample所觸發(fā)的,主要意思是對(duì)于函數(shù)中的on對(duì)應(yīng)的那一列(默認(rèn)為索引)應(yīng)該為datetime類型,所以需要將該列轉(zhuǎn)換為時(shí)間類型就可以了。
# 如果是索引
data.index = pd.to_datetime(data.index)
# 如果是普通列
df['date'] = pd.to_datetime(df['date'])