我需要重新采样由两个级别组成的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()
答案 0 :(得分:1)
尝试:
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。
接下来,对level
parameter for MultiIndex使用重采样。
level参数可以使用str,索引级别名称(例如,在这种情况下为'date')或级别编号。
最后,链和聚集功能,例如last
。