Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python计算增量平均值_Python_Pandas - Fatal编程技术网

使用python计算增量平均值

使用python计算增量平均值,python,pandas,Python,Pandas,我想生成一个时间序列的增量平均值序列。这意味着,从第一个日期(索引0)开始,存储在第x行中的平均值是值[0:x]的平均值 data index value mean formula 0 4 1 5 2 6 3 7 5.5 average(0-3) 4 4 5.2 average(0-4) 5 5 5.166666667

我想生成一个时间序列的增量平均值序列。这意味着,从第一个日期(索引0)开始,存储在第x行中的平均值是值[0:x]的平均值

data
index   value   mean          formula
0       4
1       5
2       6
3       7       5.5           average(0-3)
4       4       5.2           average(0-4)
5       5       5.166666667   average(0-5)
6       6       5.285714286   average(0-6)
7       7       5.5           average(0-7)

我希望有一种方法可以做到这一点,而不必循环利用熊猫。

正如@TomAugspurger所指出的,您可以使用:


另一种方法是使用cumsum(),然后除以累计项数,例如:

In [1]:
    s = pd.Series([4, 5, 6, 7, 4, 5, 6, 7])
    s.cumsum() / pd.Series(np.arange(1, len(s)+1), s.index)

Out[1]:
0    4.000000
1    4.500000
2    5.000000
3    5.500000
4    5.200000
5    5.166667
6    5.285714
7    5.500000
dtype: float64

以下是熊猫新版本的更新(从0.18.0开始)


您正在寻找一个没有groupby的Like。请同时查看jpobst在0.18.0之后对熊猫的回答
In [1]:
    s = pd.Series([4, 5, 6, 7, 4, 5, 6, 7])
    s.cumsum() / pd.Series(np.arange(1, len(s)+1), s.index)

Out[1]:
0    4.000000
1    4.500000
2    5.000000
3    5.500000
4    5.200000
5    5.166667
6    5.285714
7    5.500000
dtype: float64
df['value'].expanding().mean()
s.expanding().mean()