熊猫累积计数

jin*_*ept 10 python pandas

我有一个这样的数据框:

0        04:10  obj1
1        04:10  obj1
2        04:11  obj1
3        04:12  obj2
4        04:12  obj2
5        04:12  obj1
6        04:13  obj2
Run Code Online (Sandbox Code Playgroud)

想要获得所有这些对象的累积计数:

idx      time   object   obj1_count   obj2_count 
0        04:10  obj1        1             0
1        04:10  obj1        2             0
2        04:11  obj1        3             0
3        04:12  obj2        3             1
4        04:12  obj2        3             2
5        04:12  obj1        4             2
6        04:13  obj2        4             3
Run Code Online (Sandbox Code Playgroud)

尝试玩cumsum但不确定这是正确的方法.有什么建议?

Ale*_*sky 13

这种操作有一个特殊功能: cumcount

>>> df = pd.DataFrame([['a'], ['a'], ['a'], ['b'], ['b'], ['a']], columns=['A'])
>>> df
   A
0  a
1  a
2  a
3  b
4  b
5  a
>>> df.groupby('A').cumcount()
0    0
1    1
2    2
3    0
4    1
5    3
dtype: int64
>>> df.groupby('A').cumcount(ascending=False)
0    3
1    2
2    1
3    1
4    0
5    0
 dtype: int64
Run Code Online (Sandbox Code Playgroud)


EdC*_*ica 8

您可以将列与感兴趣的值进行比较并调用cumsum:

In [12]:
df['obj1_count'] = (df['object'] == 'obj1').cumsum()
df['obj2_count'] = (df['object'] == 'obj2').cumsum()
df

Out[12]:
      time object  obj1_count  obj2_count
idx                                      
0    04:10   obj1           1           0
1    04:10   obj1           2           0
2    04:11   obj1           3           0
3    04:12   obj2           3           1
4    04:12   obj2           3           2
5    04:12   obj1           4           2
6    04:13   obj2           4           3
Run Code Online (Sandbox Code Playgroud)

这里的比较将产生一个布尔系列:

In [13]:
df['object'] == 'obj1'

Out[13]:
idx
0     True
1     True
2     True
3    False
4    False
5     True
6    False
Name: object, dtype: bool
Run Code Online (Sandbox Code Playgroud)

当你打电话cumsum给上面的时候,这些True值被转换为1False,0并被累加