MultiIndex 的重采样

Resampling of MultiIndex

我想要按类型对数据集进行每日细分。没有针对每种类型的每一天的记录,如果它们不存在我想要 NaN。

我能够得到 'resampled to daily' 结果,但类型被省略了。

下面的代码应该是一个完整的示例(好吧,除了最后的已知错误之外!):

import pandas as pd
import datetime as dt

df = pd.DataFrame({
    'Date': [dt.datetime(2021,1,1), dt.datetime(2021, 1, 3), dt.datetime(2020,1,2)],
    'Type': ['A', 'A', 'B'],
    'Value': [1,2,3]
})

df.set_index('Date', inplace=True)
#   this loses the 'type'
print(df.resample('1D').mean())

df = df.reset_index().set_index(['Date', 'Type'])

#   this raises an exception "TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'"
print(df.resample('1D').mean())

我正在寻找的输出是每天的一行/类型组合:

date type value
20210101 A 1
20210102 A NaN
20210103 A 2
20210101 B NaN
20210102 B 3
20210103 B NaN

非常感谢收到的任何建议或指示。

如果需要每组重新采样,可以使用 Grouper for resample per days and then for add missing values is used Series.unstack with DataFrame.stack:

df = (df.groupby(['Type', pd.Grouper(freq='1D', key='Date')])['Value']
        .mean()
        .unstack()
        .stack(dropna=False)
        .reset_index(name='Value')
      
      )
print (df)  
  Type       Date  Value
0    A 2021-01-01    1.0
1    A 2021-01-02    NaN
2    A 2021-01-03    2.0
3    B 2021-01-01    NaN
4    B 2021-01-02    3.0
5    B 2021-01-03    NaN

如果只需要追加每个组缺少的日期时间,则使用 DataFrame.reindex:

mux = pd.MultiIndex.from_product([df['Type'].unique(),
                                  pd.date_range(df['Date'].min(), df['Date'].max())], 
                                  names=['Date','Type'])
df = df.set_index(['Type','Date']).reindex(mux).reset_index()
print (df)                
  Date       Type  Value
0    A 2021-01-01    1.0
1    A 2021-01-02    NaN
2    A 2021-01-03    2.0
3    B 2021-01-01    NaN
4    B 2021-01-02    3.0
5    B 2021-01-03    NaN