python - How to rank DataFrame by subgroup -


if have dataframe such

  col1   col2  col3 0   x1  typea     3 1   x2  typeb    13 2   x3  typeb     3 3   x4  typea     5 4   x5  typeb     1 5   x6  typea     1 

is there way of ranking rows col3 each type in col2? example solution like

  col1   col2  col3  rank 0   x1  typea     3    2 1   x2  typeb    13    1 2   x3  typeb     3    2  3   x4  typea     5    1 4   x5  typeb     1    3 5   x6  typea     1    3 

transform keeps same shape original dataframe. use lambda function rank col3 based on groupings col2..

df['col4'] = df.groupby('col2').col3.transform(lambda group: group.rank())  >>> df   col1   col2  col3  col4 0   x1  typea     3     2 1   x2  typeb    13     3 2   x3  typeb     3     2 3   x4  typea     5     3 4   x5  typeb     1     1 5   x6  typea     1     1 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -