累积计数基于两个分类列

问题描述 投票:2回答:1

对于表中的每条记录,我想根据两个分类列进行累积计数。

在下表中,我想获取cum_count列,该列是根据columns行和deal_status计算的。这个想法是,对于每个记录,计算同一行业以前赢得的交易数量。

例如,该表的最后一条记录的cum_count = 3,因为之前只有3次涉及trade_x的deal_status = won的交易。

Pandas' GroupBy.cumcount function为单个变量做到了这一点......

如何根据我描述的情况完成此操作?

pd.DataFrame({'time': [1, 2, 3, 4, 5, 6, 7],
              'company' : ["ciaA", "ciaB", "ciaA", "ciaC", "ciaA", "ciaD", "ciaE"],
              'industry' : ["x", "y", "x", "x", "x", "y", "x"],
              'deal_status' : ["won", "lost", "won", "won", "lost", "won", "lost"],
              'cum_count' : [0, 0, 1, 2, 3, 0, 3]})


time    company    industry     deal_status     cum_count
 1       ciaA         x             won             0
 2       ciaB         y            lost             0
 3       ciaA         x             won             1
 4       ciaC         x             won             2
 5       ciaA         x            lost             3
 6       ciaD         y             won             0
 7       ciaE         x            lost             3
python pandas jupyter-notebook
1个回答
3
投票

创建一个辅助列,您将获取累积总和。需要在每个组内转换,因为您的计数仅包括之前的赢取值:

df['to_sum'] = (df.deal_status == 'won').astype(int)
df['cum_count'] = (df.groupby('industry')
                    .apply(lambda x: x.to_sum.shift(1).cumsum()).fillna(0)
                    .reset_index(0, drop=True))

Output df:

   time company industry deal_status  to_sum  cum_count
0     1    ciaA        x         won       1        0.0
1     2    ciaB        y        lost       0        0.0
2     3    ciaA        x         won       1        1.0
3     4    ciaC        x         won       1        2.0
4     5    ciaA        x        lost       0        3.0
5     6    ciaD        y         won       1        0.0
6     7    ciaE        x        lost       0        3.0
© www.soinside.com 2019 - 2024. All rights reserved.