Skip to main content
 首页 » 编程设计

python之Pandas.DataFrame.resample MultiIndex 的内层

2024年11月01日11bjzhanghao

我需要对包含两个级别的 Pandas MultiIndex 重新采样。内层是日期时间索引。需要重新采样。

import numpy as np 
import pandas as pd 
 
rng = pd.date_range('2019-01-01', '2019-04-27', freq='B', name='date') 
df = pd.DataFrame(np.random.randint(0, 100, (len(rng), 2)), index=rng, columns=['sec1', 'sec2']) 
 
df['month'] = df.index.month 
df.set_index(['month', rng], inplace=True) 
print(df) 
 
# At that point I need to apply pd.resample. I'm wondering how to specify the level that I would like to resample? 
df = df.resample('M').last()  # is not working; 
# I'm looking for somthing like this: df = df.resample('M', level=1).last() 

请您参考如下方法:

尝试:

 df.groupby('month').resample('M', level=1).last() 

输出:

                  sec1  sec2 
month date                   
1     2019-01-31    59    87 
2     2019-02-28    70    33 
3     2019-03-31    71    38 
4     2019-04-30    56    79 

详细信息。

首先,将数据帧分组到索引的“月”或级别=0。
接下来,将 resample 与 level parameter for MultiIndex 一起使用. level 参数可以使用 str、索引级别名称(在本例中为“date”)或级别编号。
最后,链和聚合函数,如last。