Skip to main content

Python Pandas Sorting Dataframe In Ascending or Descending Order Based On Single or Multiple Columns (Example)

Sorting pandas dataframe by single or multiple columns.
DataFrame has "sort_values()" method which can be used to sort the dataframe based single or multiple columns , control sorting flow and choose ascending or descending order.


Creating a new dataframe with dictionary 


# importing pandas
import pandas as pd
import numpy as np

# animal_data dictionary
animal_data = {
    "Name": ["Cat", "Dog", "Cow"],
    "Speed": [15, 12, 10],
    "Sound": ["Meow", "Woof", "Mooo"],
    "Rank": [1, 5, 3],
    "Jumping_height": [20, 10, np.NaN],
}

# creating a dataframe using the animal_data dictionary
animal_df = pd.DataFrame(animal_data)

# printing animal_df
print("animal_df \n", animal_df)

animal_df Name Speed Sound Rank Jumping_height 0 Cat 15 Meow 1 20.0 1 Dog 12 Woof 5 10.0 2 Cow 10 Mooo 3 NaN


Sorted in ascending order


asc_sorted_animal_df = animal_df.sort_values(
    by=["Speed"],
    ascending=True,
)

print("sorted by speed in ascending order \n", asc_sorted_animal_df)

sorted by speed in ascending order Name Speed Sound Rank Jumping_height 2 Cow 10 Mooo 3 NaN 1 Dog 12 Woof 5 10.0 0 Cat 15 Meow 1 20.0


Sorted in descending order


desc_sorted_animal_df = animal_df.sort_values(
    by=["Speed"],
    ascending=False,
)
print("sorted by speed in descending order \n", desc_sorted_animal_df)

sorted by speed in descending order Name Speed Sound Rank Jumping_height 0 Cat 15 Meow 1 20.0 1 Dog 12 Woof 5 10.0 2 Cow 10 Mooo 3 NaN


Sorted by "Speed" column values in descending order and then sorted by "Rank" column values in ascending order


sorted_by_multi_col = animal_df.sort_values(
    by=["Rank", "Speed"],
    ascending=[True, False],
)

# the df shows it has been sorted in ascending order based on Rank as the last operation
# [Speed 0 , Rank 1 ]
print(
    "sorted by speed in descending order \n and then sorted by rank in ascending order \n",
    sorted_by_multi_col,)

sorted by speed in descending order and then sorted by rank in ascending order Name Speed Sound Rank Jumping_height 0 Cat 15 Meow 1 20.0 2 Cow 10 Mooo 3 NaN 1 Dog 12 Woof 5 10.0

Comments

Topics

Show more