How to Sort CSV by a single column in Python ?

PythonServer Side ProgrammingProgramming

To sort CSV by a single column, use the sort_values() method. Set the column using which you want to sort in the sort_values() method.

At first, let’s read our CSV file “SalesRecords.csv”with DataFrame −

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

Sort according to a single column “Car” −

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

Next, sort according to a single column “Reg_Price” −

dataFrame.sort_values("Reg_Price", 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 Car column
dataFrame.sort_values("Car", axis=0, ascending=True,inplace=True, na_position='first')

print("\nSorted CSV file (according to Car Names) = \n", dataFrame)

# sorting according to Reg_Price column
dataFrame.sort_values("Reg_Price", axis=0, ascending=True,inplace=True, na_position='first')

print("\nSorted CSV file (according to Registration Price) = \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         Audi         10/12/2020         750
2        Lexus         10/17/2020        1250
3       Jaguar         10/16/2020        1500
4      Mustang         10/19/2020        1100
5  Lamborghini         10/22/2020        1000

Sorted CSV file (according to Car Names) =
           Car   Date_of_Purchase   Reg_Price
1         Audi         10/12/2020         750
0          BMW         10/10/2020        1000
3       Jaguar         10/16/2020        1500
5  Lamborghini         10/22/2020        1000
2        Lexus         10/17/2020        1250
4      Mustang         10/19/2020        1100

Sorted CSV file (according to Registration Price) =
           Car   Date_of_Purchase   Reg_Price
1         Audi         10/12/2020         750
0          BMW         10/10/2020        1000
5  Lamborghini         10/22/2020        1000
4      Mustang         10/19/2020        1100
2        Lexus         10/17/2020        1250
3       Jaguar         10/16/2020        1500
raja
Published on 27-Sep-2021 12:25:25
Advertisements