我有一个数据帧,看起来像这样:
pd.DataFrame({'category': [1,1,1,2,2,2,3,3,3,4],
'order_start': [1,2,3,1,2,3,1,2,3,1],
'time': [1, 4, 3, 6, 8, 17, 14, 12, 13, 16]})
Out[40]:
category order_start time
0 1 1 1
1 1 2 4
2 1 3 3
3 2 1 6
4 2 2 8
5 2 3 17
6 3 1 14
7 3 2 12
8 3 3 13
9 4 1 16
我想创建一个新的列,其中包含相同类别以前的平均值。如何创建它?在
新列应该如下所示:
^{pr2}$注:如果是第一次,平均值应为NaN。在
编辑:正如cs95所说,我的问题实际上与this one不一样,因为这里需要扩展。在
“create a new column that containing the means of the previous times of the same category”听起来是
GroupBy.expanding
的一个很好的用例(还有一个移位):另一种计算方法是不使用
^{pr2}$apply
(链接两个groupby
调用):就表现而言,这实际上取决于团队的数量和规模。在
相关问题 更多 >
编程相关推荐