How to Sort CSV by multiple columns in Python ?

PythonServer Side ProgrammingProgramming

To sort CSV by multiple columns, use the sort_values() method. Sorting by multiple columns means if one of the columns has repeated values, then the sort order depends on the 2nd column mentioned under sort_values() method.

At first, let us read our input CSV file “SalesRecords.csv” −

dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")

Let us now sort according to multiple columns i.e. “Reg_Price” and “Car” −

dataFrame.sort_values(["Reg_Price","Car"],axis=0, ascending=True,inplace=True,na_position='first')

Example

Following is the code −

import pandas as pd

# DataFrame to read our input CS file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
print("\nInput CSV file = \n", dataFrame)

# sorting according to multiple columns
dataFrame.sort_values(["Reg_Price","Car"],axis=0, ascending=True,inplace=True,na_position='first')

print("\nSorted CSV file (according to multiple columns) = \n", dataFrame)

Output

This will produce the following output −

Input CSV file =
           Car   Date_of_Purchase   Reg_Price
0          BMW         10/10/2020        1000
1        Lexus         10/12/2020         750
2         Audi         10/17/2020         750
3       Jaguar         10/16/2020        1500
4      Mustang         10/19/2020        1100
5  Lamborghini         10/22/2020        1000

Sorted CSV file (according to multiple columns) =
           Car   Date_of_Purchase   Reg_Price
2         Audi         10/17/2020         750
1        Lexus         10/12/2020         750
0          BMW         10/10/2020        1000
5  Lamborghini         10/22/2020        1000
4      Mustang         10/19/2020        1100
3       Jaguar         10/16/2020        1500
raja
Published on 04-Oct-2021 06:55:31
Advertisements