【问题标题】:Cumulative count in a pandas dfpandas df中的累积计数
【发布时间】:2018-12-27 01:48:48
【问题描述】:

我正在尝试基于pandasdf 中的两列导出cumulativecount。

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

所以count 增加了second row 所以1 到Value A。 Count 在row 4 上再次增加,这是Value C 第一次所以1。 rows 5 和 7 也是如此。 count 在 row 8 上增加,所以 A 变为 2。

【问题讨论】:

    标签: python pandas count cumulative-sum


    【解决方案1】:

    您可以使用str.get_dummies 和diff 和cumsum

    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
    

    【讨论】:

    • 天哪,@Zero 很快。谢谢
    猜你喜欢
    • 2019-08-10
    • 1970-01-01
    • 2018-12-04
    • 2020-06-13
    • 2017-01-30
    • 2018-12-05
    • 2021-03-21
    • 2020-10-08
    • 1970-01-01
    相关资源
    最近更新 更多