【问题标题】:Python - Running Average If number is great than 0Python - 如果数字大于 0,则运行平均值
【发布时间】:2019-01-13 17:02:03
【问题描述】:

我的数据框中有一列由数字组成。我想在数据框中有另一列,该列采用大于 0 的值的运行平均值,我可以在 numpy 中理想地执行而无需迭代。 (数据量很大)

Vals    Output
-350    
1000    1000
1300    1150
1600    1300
1100    1250
1000    1200
450     1075
1900    1192.857143
-2000   1192.857143
-3150   1192.857143
1000    1168.75
-900    1168.75
800     1127.777778
8550    1870

代码:

list =[-350,    1000,   1300,   1600,   1100,   1000,   450,
    1900,   -2000,  -3150,  1000,   -900,   800,    8550]
    df = pd.DataFrame(data = list)

【问题讨论】:

  • 旁注,不要隐藏内置插件,使用L 而不是list

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


【解决方案1】:

选项 1
expandingmean

df.assign(out=df.loc[df.Vals.gt(0)].Vals.expanding().mean()).ffill()

如果您的 DataFrame 中有其他列具有 NaN 值,则此方法也将 ffill 这些列,因此如果这是一个问题,您可能需要考虑使用类似这样的方法:

df['Out'] = df.loc[df.Vals.gt(0)].Vals.expanding().mean()
df['Out'] = df.Out.ffill()

这只会填写Out 列。

选项 2
mask

df.assign(Out=df.mask(df.Vals.lt(0)).Vals.expanding().mean())

这两个结果都是:

    Vals          Out
0   -350          NaN
1   1000  1000.000000
2   1300  1150.000000
3   1600  1300.000000
4   1100  1250.000000
5   1000  1200.000000
6    450  1075.000000
7   1900  1192.857143
8  -2000  1192.857143
9  -3150  1192.857143
10  1000  1168.750000
11  -900  1168.750000
12   800  1127.777778
13  8550  1870.000000

【讨论】:

  • @novawaly 我个人认为我的第二个解决方案(面具)更直接,所以我建议使用它。
猜你喜欢
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 2019-03-07
  • 2010-12-19
  • 2020-05-02
  • 2017-06-11
  • 1970-01-01
  • 2016-01-02
相关资源
最近更新 更多