【问题标题】:How to apply rolling mean function by axis 1 python如何通过轴1 python应用滚动平均函数
【发布时间】:2020-05-13 08:50:44
【问题描述】:

我们可以简单地按轴计算平均值:

import pandas as pd

df=pd.DataFrame({'A':[1,1,0,1,0,1,1,0,1,1,1],
                 'b':[1,1,0,1,0,1,1,0,1,1,1],
                 'c':[1,1,0,1,0,1,1,0,1,1,1]}) 

# max_of_three columns 
mean= np.max(df.mean(axis=1))

如何用滚动平均值做同样的事情?

我试过1:

# max_of_three columns 
mean=df.rolling(2).mean(axis=1)

收到此错误:

UnsupportedFunctionCall:numpy 操作对窗口对象无效。改用 .rolling(...).mean()

我试过2:

def tt(x):
    x=pd.DataFrame(x)
    b1=np.max(x.mean(axis=1))
    return b1

# max_of_three columns 
mean=df.rolling(2).apply(tt,raw=True)

但是从这里我得到三列结果,实际上每个移动窗口应该是 1 个值。

我在哪里做错了?或任何其他有效的方法。

【问题讨论】:

    标签: python-3.x pandas numpy pandas-groupby


    【解决方案1】:

    您使用 axis 参数滚动为:

    df.rolling(2, axis=0).mean()
    >>>       A    b    c
        0   NaN  NaN  NaN
        1   1.0  1.0  1.0
        2   0.5  0.5  0.5
        3   0.5  0.5  0.5
        4   0.5  0.5  0.5
        5   0.5  0.5  0.5
        6   1.0  1.0  1.0
        7   0.5  0.5  0.5
        8   0.5  0.5  0.5
        9   1.0  1.0  1.0
        10  1.0  1.0  1.0
    
    r = df.rolling(2, axis=1).mean()
    r
    >>>      A    b    c
        0  NaN  1.0  1.0
        2  NaN  0.0  0.0
        3  NaN  1.0  1.0
        4  NaN  0.0  0.0
        5  NaN  1.0  1.0
        6  NaN  1.0  1.0
        7  NaN  0.0  0.0
        8  NaN  1.0  1.0
        9  NaN  1.0  1.0
        10 NaN  1.0  1.0
    
    r.max()
    >>> A    NaN
        b    1.0
        c    1.0
        dtype: float64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2012-06-03
      • 2013-05-07
      • 1970-01-01
      • 2015-07-26
      • 2019-01-20
      相关资源
      最近更新 更多