简体   繁体   中英

How to create a new column with a conditional count in a groupby pandas dataFrame

I have a DataFrame with a few features, something like this:

GEST    GERE    HOL
ONE1    1234    1
ONE1    6797    0
TWO2    6352    1
TWO2    5530    1

I want to group by GEST and create a new column Count if HOL == 1 and assign it for GEST .

GEST    GERE    HOL    Count
ONE1    1234    1      1
ONE1    6797    0      1
TWO2    6352    1      2
TWO2    5530    1      2
df['Count']=df.groupby('GEST')['HOL'].transform('sum')

Output

GEST    GERE    HOL    Count
ONE1    1234    1      1
ONE1    6797    0      1
TWO2    6352    1      2
TWO2    5530    1      2

If the input is a categorical value like 'Yes/No` as below

    GEST    GERE    HOL
0   ONE1    1234    Yes
1   ONE1    6797    No
2   TWO2    6352    Yes
3   TWO2    5530    Yes

You can use the code below to get the desired output

df['Count']=df.groupby('GEST')['HOL'].transform(lambda x : x.loc[x=='Yes'].count())

Output

    GEST    GERE    HOL     Count
0   ONE1    1234    Yes     1
1   ONE1    6797    No      1
2   TWO2    6352    Yes     2
3   TWO2    5530    Yes     2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM