Python - 运行平均值如果数字大于0

nov*_*aly 3 python numpy dataframe python-3.x pandas

我的数据框中有一个由数字组成的列.我喜欢在数据框中有另一个列,它采用大于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
Run Code Online (Sandbox Code Playgroud)

码:

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

use*_*203 5

选项1
expandingmean

df.assign(out=df.loc[df.Vals.gt(0)].Vals.expanding().mean()).ffill()
Run Code Online (Sandbox Code Playgroud)

如果你的DataFrame中有其他列有NaN值,那么这个方法ffill也是如此,所以如果这是一个问题,你可能要考虑使用这样的东西:

df['Out'] = df.loc[df.Vals.gt(0)].Vals.expanding().mean()
df['Out'] = df.Out.ffill()
Run Code Online (Sandbox Code Playgroud)

这只会填写Out专栏.

选项2
mask:

df.assign(Out=df.mask(df.Vals.lt(0)).Vals.expanding().mean())
Run Code Online (Sandbox Code Playgroud)

这两个导致:

    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
Run Code Online (Sandbox Code Playgroud)