Skip to main content
 首页 » 编程设计

python之使用 pandas.MultiIndex : Resampler. aggregate() & Resampler[column] 进行重采样

2025年05月04日18shihaiming

我正在尝试对数据框重新采样。首先,我想在结果中保留几个聚合。其次,对特定列有一个额外的感兴趣的聚合。由于此聚合仅与单个列相关,因此可以将重采样器限制在该列上,以免不必要地将聚合应用于其他列。

此场景适用于简单的一维列索引:

import numpy as np 
import pandas as pd 
df = pd.DataFrame(data=np.random.rand(50,4), index=pd.to_datetime(np.arange(0, 50), unit="s"), columns=["a", "b", "c", "d"]) 
r = df.resample("10s") 
result = r.aggregate(["mean", "std"]) 
result[("d", "ffill")] = r["d"].ffill() 
print(result) 

但是,一旦我开始使用多索引列,问题就出现了。首先,我不能一次保留多个聚合:

df.columns = pd.MultiIndex.from_product([("a", "b"), ("alpha", "beta")]) 
r = df.resample("10s")    # can be omitted 
result = r.aggregate(["mean", "std"]) 
---> AttributeError: 'Series' object has no attribute 'columns' 

其次,重采样器不再局限于相关列:

r[("b", "beta")].ffill() 
--> KeyError: "Columns not found: 'b', 'beta'" 

如何将我的关注点从简单索引转变为多索引?

请您参考如下方法:

你可以使用pd.Grouper在 groupby 中而不是重新采样,例如:

result = df.groupby(pd.Grouper(freq='10s',level=0)).aggregate(["mean", "std"]) 
print (result) 
                           a                                       b  \ 
                        alpha                beta               alpha    
                         mean       std      mean       std      mean    
1970-01-01 00:00:00  0.460569  0.312508  0.476511  0.260534  0.479577    
1970-01-01 00:00:10  0.441498  0.315277  0.487855  0.306068  0.535842    
1970-01-01 00:00:20  0.569884  0.248503  0.320552  0.288479  0.507755    
1970-01-01 00:00:30  0.478037  0.262654  0.552214  0.251581  0.505132    
1970-01-01 00:00:40  0.611227  0.328916  0.473773  0.241604  0.358298    
 
 
                                   beta             
                          std      mean       std   
1970-01-01 00:00:00  0.357493  0.448487  0.294432   
1970-01-01 00:00:10  0.259145  0.472250  0.320954   
1970-01-01 00:00:20  0.369490  0.432944  0.150473   
1970-01-01 00:00:30  0.298759  0.381614  0.248785   
1970-01-01 00:00:40  0.203831  0.381412  0.374965   

对于第二部分,我不太确定你的意思,但是根据单列级别的情况给出的结果,试试这个它给出了一个结果

result[("b", "beta",'ffill')] = df.groupby(pd.Grouper(freq='10s',level=0))[[("b", "beta")]].first()