温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - pandas groupby rolling mean/median with dropping missing values

python - pandas 分组平均值/中位数,缺失值下降

发布于 2020-03-27 11:11:10

如何通过滚动平均值/中位数和丢失缺失值来进入 pandas 群?也就是说,输出应在计算均值/中位数之前丢弃缺失值,而不是在存在缺失值时不给我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))

(两者都引发异常,但是可能存在一些界限)

谢谢您的帮助!

查看更多

查看更多

提问者
S.V
被浏览
65
cs95 2019-07-03 22:40

您在找min_periods什么?请注意,您不需要applyGroupBy.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