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

标签 python python-3.x pandas numpy dataframe

我的数据框中有一列由数字组成。我想在数据框中有另一列,它采用大于 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)

最佳答案

选项 1
expandingmean

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

如果您的 DataFrame 中的其他列具有 NaN 值,此方法也会填充这些值,因此如果担心这一点,您可能需要考虑使用像这样:

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

这只会填充 Out 列。

选项 2
掩码:

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

关于Python - 如果数字大于 0,则运行平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51712650/

相关文章:

python - 在数据帧的新列中返回 TextBlob 正、负或中性分类

python - 更新了 : reshape each row data into a (x, 1) 数组

python-3.x - plotly 有办法将 x 轴上的日期转换为一周中的某一天吗?

python - Linux nohup 命令无法正常工作

python - 查找单个地理数据框中所有多边形中包含的重叠区域

python - 如何在 Python 导入中跳过中间文件夹?

python - HTML 表格到 Pandas 表格 : Info inside html tags

Python:如何将 sklearn 函数与数据帧一起使用?

python - 在 Python 中进入交互模式

python - Jupyter/Plotly - 如何从 add_trace 替换或更新绘图?