How to do a conditional if statement filter after groupby

Viewed 41

I am trying to filter out rows within a group based on the string value of the ApplicationStatus field. Here's the table:

Primary Application Total Request ApplicationStatus
Application 1 10,000 Approved
Application 1 10,000 Declined
Application 2 15,000 Approved
Application 2 30,000 Declined
Application 3 50,000 Declined
Application 3 20,000 Locked

I've been trying to write a function that, if row 1 is "Approved," then delete the second row of the group, and if row 1 is "Declined," then delete the first row of the group. Here's my expected output:

Primary Application Total Request ApplicationStatus
Application 1 10,000 Approved
Application 2 15,000 Approved
Application 3 20,000 Locked

Here's my attempted code:

df_Group = df.groupby("Primary Application").apply(lambda x: x.loc[0] if x.ApplicationStatus == 'Approved' else x.loc[1])
2 Answers
df_Group = df.groupby("Primary_Application", as_index=False).apply(
    lambda x: x.iloc[0]
    if x["ApplicationStatus"].iat[0] == "Approved"
    else x.iloc[1]
)
print(df_Group)

Prints:

  Primary_Application Total_Request ApplicationStatus
0       Application 1        10,000          Approved
1       Application 2        15,000          Approved
2       Application 3        20,000            Locked

simple way can be (for above usecase data, Declined is not accepted here) :

df[~(df['ApplicationStatus'] =='Declined')]

  Primary Application Total Request ApplicationStatus
0       Application 1        10,000          Approved
2       Application 2        15,000          Approved
5       Application 3        20,000            Locked
Related