从汇总类别创建新列 [英] Create new columns from aggregated categories

查看:64
本文介绍了从汇总类别创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,看起来像:

I have a dataframe looks like:

    SK_ID_CURR  CREDIT_ACTIVE
0   215354  Closed
1   215354  Active
2   215354  Active
3   215354  Active
4   215354  Active
5   215354  Active
6   215354  Active
7   162297  Closed
8   162297  Closed
9   162297  Active

我想汇总每个ID的有效信用和封闭信用的数量,然后为Active_creditsClosed_credits新建一个列,其中包含每个ID对应的有效信用和封闭信用的数量.

I would like to aggregate the number of active and closed credits for each id, and then make a new column for Active_credits, Closed_credits with the number of corresponding active and closed credits for each id.

推荐答案

您可以使用 pandas.crosstab ,它避免了您建议的中介步骤:

You can use pandas.crosstab, which avoids your suggested intermediary step:

res = pd.crosstab(df['SK_ID_CURR'], df['CREDIT_ACTIVE'])

print(res)

CREDIT_ACTIVE  Active  Closed
SK_ID_CURR                   
162297              1       2
215354              6       1

这篇关于从汇总类别创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆