Assiging a rank to each group in pandas

30
August 10, 2018, at 1:40 PM

I have a dataframe and would like to assign a rank to each row in a group. For example,

A,B,C,D,E
---------
1,2,5,3,5
2,4,5,4,3
1,2,3,4,5
2,4,4,5,6
3,5,6,7,7

So I'd like to group by columns A and B and then assign a rank based on the value of column C but I'd like to keep the D and E as well. If I do a group by, I have to drop the D and E. What's the easiest way to do this?

Answer 1

I would do the following:

df['rank'] = df.groupby(['A', 'B'])['C'].transform(lambda x: x.rank())
READ ALSO
The correct way to shorten long for statement to a maximum of 79 columns

The correct way to shorten long for statement to a maximum of 79 columns

My question is what's the most conventional way of making the following line of code:

40
Understanding output from statsmodels grangercausalitytests

Understanding output from statsmodels grangercausalitytests

I'm new to Granger Causality and would appreciate any advice on understanding/interpreting the results of the python statsmodels outputI've constructed two data sets (sine functions shifted in time with noise added)

37
How to update the key names in place in a complex Python dictionary

How to update the key names in place in a complex Python dictionary

I struggled with this yesterday afternoon and think I have come up with a clever solution but looking for feedback on how to improve it

20