Zack
Zack

Reputation: 349

Rank a column based on 2 conditions in pandas

I have a df as such

df col_a col_b 0 ADD 5 1 ADD 2 2 ADD 8 3 DELETE 3 4 DELETE 7 5 DELETE 4 now i want to rank the values in col_b when col_a = ADD and then rank the values in col_b where col_a = DELETE. So have two separate rank values but within one column. i have the code which ranks based on one condition but can some help me with two conditions. thanks

df['Rank'] = df.col_b[df['col_a'] == 'ADD'].rank()

Upvotes: 1

Views: 28

Answers (1)

Eric Truett
Eric Truett

Reputation: 3010

Use df.groupby().rank()

df['rank'] = df.groupby('col_a')['col_b'].rank()

Upvotes: 1

Related Questions