首页 > 解决方案 > pandas df中的累积计数

问题描述

我正在尝试cumulative count基于 a 中的两列导出 a pandas df

下面是一个例子df。我正在尝试导出count基于ValueCount. 因此,当count增加我想将其归因于相邻的value

import pandas as pd

d = ({
    'Value' : ['A','A','B','C','D','A','B','A'],
    'Count' : [0,1,1,2,3,3,4,5],
    }) 

df = pd.DataFrame(d)

我用过这个:

for val in ['A','B','C','D']:
    cond = df.Value.eq(val) & df.Count.eq(int)
    df.loc[cond, 'Count_' + val] = cond[cond].cumsum()

如果我更改int为特定数字,它将返回计数。Count但是随着列的不断增加,我需要这个来读取任何数字。

我的预期输出是:

  Value  Count  A_Count  B_Count  C_Count  D_Count
0     A      0        0        0        0        0
1     A      1        1        0        0        0
2     B      1        1        0        0        0
3     C      2        1        0        1        0
4     D      3        1        0        1        1
5     A      3        1        0        1        1
6     B      4        1        1        1        1
7     A      5        2        1        1        1

所以就count增加second rowso 1to Value ACount再次增加,这row 4是第一次。和再次相同。就这样增加了。Value C1rows 57countrow 8A2

标签: pythonpandascountcumulative-sum

解决方案


你可以使用str.get_dummiesanddiffcumsum

In [262]: df['Value'].str.get_dummies().multiply(df['Count'].diff().gt(0), axis=0).cumsum()
Out[262]:
   A  B  C  D
0  0  0  0  0
1  1  0  0  0
2  1  0  0  0
3  1  0  1  0
4  1  0  1  1
5  1  0  1  1
6  1  1  1  1
7  2  1  1  1

哪个是

In [266]: df.join(df['Value'].str.get_dummies()
                  .multiply(df['Count'].diff().gt(0), axis=0)
                  .cumsum().add_suffix('_Count'))
Out[266]:
  Value  Count  A_Count  B_Count  C_Count  D_Count
0     A      0        0        0        0        0
1     A      1        1        0        0        0
2     B      1        1        0        0        0
3     C      2        1        0        1        0
4     D      3        1        0        1        1
5     A      3        1        0        1        1
6     B      4        1        1        1        1
7     A      5        2        1        1        1

推荐阅读