Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.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_Pandas Groupby - Fatal编程技术网

Python 我如何计算每组的移动扩展平均值

Python 我如何计算每组的移动扩展平均值,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我希望在groupby('col1')的基础上扩展col2的平均值,但我希望平均值不包括行本身(仅包括它上面的行) 我本以为他们的结果是一样的。 预期的结果是两条直线。一行在两组之间混合数字 这个解决方案花了很长时间,有人能解释一下逻辑吗?为什么一行不能给出预期的结果?您正在groupby()中查找expansing().mean()和shift(): 输出: col1 col2 one_liner two_liner 0 a 1 NaN Na

我希望在groupby('col1')的基础上扩展col2的平均值,但我希望平均值不包括行本身(仅包括它上面的行)

我本以为他们的结果是一样的。 预期的结果是两条直线。一行在两组之间混合数字


这个解决方案花了很长时间,有人能解释一下逻辑吗?为什么一行不能给出预期的结果?

您正在
groupby()中查找
expansing().mean()
shift()

输出:

  col1  col2  one_liner  two_liner
0    a     1        NaN        NaN
1    a     2        1.0        NaN
2    a     3        1.5        1.0
3    b     4        NaN        NaN
4    b     5        4.0        NaN
5    b     6        4.5        4.0
6    c     7        NaN        NaN
7    c     8        7.0        NaN
说明:

(dummy.groupby('col1').col2.shift()   # this shifts col2 within the groups 
     .expanding().mean()              # this ignores the grouping and expanding on the whole series
     .reset_index(level=0, drop=True) # this is not really important
)
因此,上述链接命令等效于

s1 = dummy.groupby('col1').col2.shift()
s2 = s1.expanding.mean()
s3 = s2.reset_index(level=0, drop=True)
如您所见,只有
s1
考虑按
col1
分组

(dummy.groupby('col1').col2.shift()   # this shifts col2 within the groups 
     .expanding().mean()              # this ignores the grouping and expanding on the whole series
     .reset_index(level=0, drop=True) # this is not really important
)
s1 = dummy.groupby('col1').col2.shift()
s2 = s1.expanding.mean()
s3 = s2.reset_index(level=0, drop=True)