如何通过滚动平均值/中位数并删除缺失值来进入 Pandas 组? IE。如果存在缺失值,则输出应在计算平均值/中位数之前删除缺失值,而不是给我 NaN。

import pandas as pd
t = pd.DataFrame(data={v.date:[0,0,0,0,1,1,1,1,2,2,2,2],
                         'i0':[0,1,2,3,0,1,2,3,0,1,2,3],
                         'i1':['A']*12,
                         'x':[10.,20.,30.,np.nan,np.nan,21.,np.nan,41.,np.nan,np.nan,32.,42.]})
t.set_index([v.date,'i0','i1'], inplace=True)
t.sort_index(inplace=True)

print(t)
print(t.groupby('date').apply(lambda x: x.rolling(window=2).mean()))



               x
date i0 i1
0    0  A   10.0
     1  A   20.0
     2  A   30.0
     3  A    NaN
1    0  A    NaN
     1  A   21.0
     2  A    NaN
     3  A   41.0
2    0  A    NaN
     1  A    NaN
     2  A   32.0
     3  A   42.0

               x
date i0 i1
0    0  A    NaN
     1  A   15.0
     2  A   25.0
     3  A    NaN
1    0  A    NaN
     1  A    NaN
     2  A    NaN
     3  A    NaN
2    0  A    NaN
     1  A    NaN
     2  A    NaN
     3  A   37.0

虽然我想要这个例子的以下内容:

               x
date i0 i1
0    0  A   10.0
     1  A   15.0
     2  A   25.0
     3  A   30.0
1    0  A    NaN
     1  A   21.0
     2  A   21.0
     3  A   41.0
2    0  A    NaN
     1  A    NaN
     2  A   32.0
     3  A   37.0

我试过的

t.groupby('date').apply(lambda x: x.rolling(window=2).dropna().median())



t.groupby('date').apply(lambda x: x.rolling(window=2).median(dropna=True))

(两者都引发异常,但也许存在一些沿线的东西)

感谢您的帮助!

最佳答案

您在寻找 min_periods 吗?注意不需要 apply ,直接调用 GroupBy.Rolling :

t.groupby('date', group_keys=False).rolling(window=2, min_periods=1).mean()
               x
date i0 i1
0    0  A   10.0
     1  A   15.0
     2  A   25.0
     3  A   30.0
1    0  A    NaN
     1  A   21.0
     2  A   21.0
     3  A   41.0
2    0  A    NaN
     1  A    NaN
     2  A   32.0
     3  A   37.0

关于python - pandas groupby 滚动平均值/中值并删除缺失值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56872205/

10-12 20:27