Skip to content Skip to sidebar Skip to footer

Sort By Frequency Of Values In A Column - Pandas

I have a column in a dataframe Fruits Apple Mango Banana Apple

Solution 1:

Create a freq column and then sort by freq and fruit name.

df.assign(freq=df.apply(lambda x: df.Fruits.value_counts()\
  .to_dict()[x.Fruits], axis=1))\
  .sort_values(by=['freq','Fruits'],ascending=[False,True]).loc[:,['Fruits']]
Out[593]: 
   Fruits0Apple3Apple6Apple1Mango4Mango7Mango2Banana5Banana8Grapes

A similar approach by using groupby and count:

df.assign(freq=df.groupby('Fruits')['Fruits'].transform('count'))\
  .sort_values(by=['freq','Fruits'],ascending=[False,True]).loc[:,['Fruits']]

Post a Comment for "Sort By Frequency Of Values In A Column - Pandas"