熊猫df中的累积计数

时间:2018-07-19 03:29:00

标签: python pandas count cumulative-sum

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

一个例子是下面的df。我正在尝试基于countValue导出Count。因此,当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

因此countsecond row上增加,因此1Value ACountrow 4上再次增加,这是Value C的第一次,因此1。对于rows 57同样如此。 countrow 8上增加,因此A变成2

1 个答案:

答案 0 :(得分:2)

您可以使用str.get_dummiesdiffcumsum

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