Home > Enterprise >  Using .sort_values() in Python
Using .sort_values() in Python

Time:02-22

I am trying to figure out how to sort a dataframe base on the values of a column.

At the moment, it is re-organising the dataframe order, but not in order of smallest -> largest or largest -> smallest. It seems to be a random order.

enter image description here

What am I doing wrong?

CodePudding user response:

It looks like the Impressions column is stored as a string rather than as an int. So, it's sorting the digit representations in "alphabetical" order.

One solution is to change the values to int within the data frame. Another is to use a key for the sort_values call that converts the string to a number.

CodePudding user response:

The second option that @BenGrossmann said looks like this:

data.sort_values(by='Impressions', key=lambda col: int(col.replace(",","")))

  • Related