重新采样(Upsample)Pandas multiindex数据帧

时间:2016-09-28 04:08:57

标签: python pandas dataframe multi-index resampling

以下是供参考的示例数据框:

import pandas as pd
import datetime
import numpy as np
np.random.seed(1234)

arrays = [np.sort([datetime.date(2016, 8, 31), datetime.date(2016, 7, 31), datetime.date(2016, 6, 30)]*3),
         ['A', 'B', 'C', 'D', 'E']*5]
df = pd.DataFrame(np.random.randn(15, 4), index=arrays)
df.index.rename(['date', 'id'], inplace=True)

它看起来像什么:

enter image description here

我想通过上采样重新采样多索引的date级别到每周频率W-FRI,即从最近的值how='last'复制。我见过的例子通常会在使用pd.Grouper函数后聚合数据(我想避免)。

编辑:我在下面找到了一个解决方案,但我想知道是否有更有效的方法。

2 个答案:

答案 0 :(得分:2)

编辑:我找到了一个解决方案:

df.unstack().resample('W-FRI', how='last', fill_method='ffill')

但我想知道是否有更有效的方法来做到这一点。

答案 1 :(得分:0)

在当前的熊猫版本0.23.3中,您的方法将导致警告:

  

未来警告:不推荐使用fill_method.resample()

     

新语法为.resample(...)。last()。ffill()

这不会引起警告:

df.unstack(level=1).resample('W-FRI').pad()

最好明确声明拆栈级别(在您的情况下为1或-1)IMO

相关问题