Python 使用带熊猫滚动的数据帧所有值的实际平均值

Python 使用带熊猫滚动的数据帧所有值的实际平均值,python,pandas,dataframe,rolling-computation,Python,Pandas,Dataframe,Rolling Computation,如果我有这样一个df: a001 a002 1 1 NaN 7 NaN NaN NaN 3 NaN NaN 2 2 NaN

如果我有这样一个df:

    a001         a002           
      1            1             
    NaN            7             
    NaN          NaN          
    NaN            3             
    NaN          NaN         
    2              2           
    NaN            6 
如果我想计算两行窗口的平均值,我可以使用:

df['rolling_mean'] = df.mean(axis=1).rolling(window=2, min_periods=1).mean()
返回:

    a001  a002  rolling_mean
0   1.0   1.0           1.0
1   NaN   7.0           4.0
2   NaN   NaN           7.0
3   NaN   3.0           3.0
4   NaN   NaN           3.0
5   2.0   2.0           2.0
6   NaN   6.0           4.0
这是两行窗口上的平均值,使用单个行元素的平均值。因此,例如,第1(4)行中的
滚动平均值是第0行
(1+1)/2=1
的平均值和第1(7)行的值之间的平均值:
(1+7)/2=4

如果我想在前两行中取这3个值的平均值,结果应该是:
(1+1+7)/3=3
。 为了获得它,我使用了以下方法:

df2 = df.copy()
df['sum'] = df2.sum(axis=1).rolling(window=1, min_periods=1).mean()
df['count'] = df2.count(axis=1).rolling(window=1, min_periods=1).mean()
df['last_2'] = df['sum'].rolling(window=2, min_periods=1).sum() / df['count'].rolling(window=2, min_periods=1).sum()
返回所需的输出:

   a001  a002  sum  count     last_2
0   1.0   1.0  2.0    2.0   1.000000
1   NaN   7.0  7.0    1.0   3.000000
2   NaN   NaN  NaN    0.0   7.000000
3   NaN   3.0  3.0    1.0   3.000000
4   NaN   NaN  NaN    0.0   3.000000
5   2.0   2.0  4.0    2.0   2.000000
6   NaN   6.0  6.0    1.0   3.333333
我的问题是:有没有一种更优雅、更像蟒蛇的方法?感谢我的工作:

df['last_2'] = (df.sum(axis=1).rolling(window=2, min_periods=1).sum() / 
                df.count(axis=1).rolling(window=2, min_periods=1).sum())
print (df)

   a001  a002    last_2
0   1.0   1.0  1.000000
1   NaN   7.0  3.000000
2   NaN   NaN  7.000000
3   NaN   3.0  3.000000
4   NaN   NaN  3.000000
5   2.0   2.0  2.000000
6   NaN   6.0  3.333333

再次感谢你的帮助@乔-很高兴能帮上忙!