我的目标是执行 groupby,然后创建滚动总统计数据,然后移动。我需要它来转移每个独特玩家的第一个实例。现在它正在移动整个数据帧一次,而不是对每个分组的玩家都这样做。
原始数据-
player date won
0 A 2016-01-11 0
1 A 2016-02-01 0
2 A 2016-02-01 1
3 A 2016-02-01 1
4 A 2016-10-24 0
5 A 2016-10-31 0
6 A 2018-10-22 0
7 B 2016-10-24 0
8 B 2016-10-24 1
9 B 2017-11-13 0
我尝试过的事情 -
1
temp = temp_master.groupby('player', sort=False)[count_fields].rolling(10, min_periods=1).sum().shift(1).reset_index(drop=True)
temp = temp.add_suffix('_total')
temp['won_total'].head(10)
0 NaN
1 0.0
2 0.0
3 1.0
4 2.0
5 2.0
6 2.0
7 2.0
8 0.0
9 1.0
2
temp = temp_master.groupby('player', sort=False)[count_fields].shift(1).rolling(10, min_periods=1).sum().reset_index(drop=True)
temp = temp.add_suffix('_total')
temp['won_total'].head(10)
0 NaN
1 0.0
2 0.0
3 1.0
4 2.0
5 2.0
6 2.0
7 2.0
8 2.0
9 3.0
3
temp = temp_master.groupby('player', sort=False)[count_fields].rolling(10, min_periods=1).sum().reset_index(drop=True)
temp = temp.add_suffix('_total')
temp = temp.shift(1)
temp['won_total'].head(10)
0 NaN
1 0.0
2 0.0
3 1.0
4 2.0
5 2.0
6 2.0
7 2.0
8 0.0
9 1.0
这就是我需要的结果 -
0 NaN
1 0.0
2 0.0
3 1.0
4 2.0
5 2.0
6 2.0
7 NaN
8 0.0
9 1.0
索引 #7 应该等于 NaN。它应该是玩家 B 的第一个实例,我希望它在每个新玩家的第一个实例中移动,以按玩家汇总统计数据。
索引 8 应该等于 0
索引 9 应该等于 1
看起来尝试 #1 和 #3 很接近,但它没有为新玩家分配 NaN 值。 #3 不再使用 groupedby player,所以我知道这不会真正起作用。
此外,这将在大量数据(大约 100K-300K 行)上完成,并且“count_fields”列包含我正在计算的大约 3K-4K 列。只是需要注意的事情。
关于如何按球员创建运行统计数据并为每位球员下调的任何想法?
最佳答案
这里需要apply
,这两个函数不是链在groupby
对象下,sum在groupby
下,但是 shift
将执行到 sum 之后的结果,即整列
temp = temp_master.groupby('player', sort=False)['won'].apply(lambda x : x.rolling(10, min_periods=1).sum().shift(1))\
.reset_index(drop=True)
temp
0 NaN
1 0.0
2 0.0
3 1.0
4 2.0
5 2.0
6 2.0
7 NaN
8 0.0
9 1.0
Name: won, dtype: float64
关于python - 计算每组的滚动总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54163080/