gpt4 book ai didi

python - 使用 pandas 滚动对数据帧的所有值进行实际平均值

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:34 25 4
gpt4 key购买 nike

如果我有这样的 df:

    a001         a002           
1 1
NaN 7
NaN NaN
NaN 3
NaN NaN
2 2
NaN 6

如果我想计算 2 行窗口的平均值,我可以使用这个:

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

这是 2 行窗口的平均值,使用单行元素的平均值。例如,row1 (4) 中的 rolling_mean 是 row0 (1+1)/2 = 1 的平均值与 row1 (7) 的值之间的平均值:(1+7)/2 = 4

如果我想要前 2 行中这 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

我的问题是:有没有更优雅和Pythonic的方法来做到这一点?谢谢

最佳答案

对我来说:

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

关于python - 使用 pandas 滚动对数据帧的所有值进行实际平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49422329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com