How to apply a conditional after use groupby in pandas

37 Views Asked by At

I have a question with pandas,

I have the following code to group by State and sum the number of rows that in the String "Measure name" contains the word 'Death',

state_grp = df.groupby(['State'])
state_grp['Measure name'].apply(lambda x: x.str.contains('Death').sum())

Result:

State Sum
AK 123
DC 24

but after obtaining the result i want to apply another conditional regarding the acronym of the state, for example if State contains the letter A multiply the 'Sum' by 2.

Final result:

State Sum
AK 246
DC 24

I tried again with .apply(lambda x: ..) but I didn't get what I wanted,

I am new to pandas and I want to understand how to do it for study purposes.

1

There are 1 best solutions below

2
Andrej Kesely On

After the grouping/summing you can create a boolean mask using .str.contains() and then use this mask in df.loc[]:

mask = df["State"].str.contains("A")
df.loc[mask, "Sum"] *= 2

print(df)

Prints:

  State  Sum
0    AK  246
1    DC   24

EDIT: When the result of grouping/summing is series, you can construct the mask slightly differently:

mask = df.index.str.contains("A")
df.loc[mask, "Sum"] *= 2

print(df)  # or print(df.reset_index())

Prints:

       Sum
State     
AK     246
DC      24