如何在 Python 中按单列对 CSV 进行排序?

pythonserver side programmingprogramming更新于 2025/11/17 0:44:17

要按单列对 CSV 进行排序,请使用 sort_values() 方法。在 sort_values() 方法中设置要排序的列。

首先,让我们使用 DataFrame − 读取我们的 CSV 文件"SalesRecords.csv"

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

根据单列"Car"排序−

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

接下来,根据单个列"Reg_Price"进行排序−

dataFrame.sort_values("Reg_Price", axis=0, accending=True,inplace=True, na_position='first')

示例

以下是代码

import pandas as pd

# DataFrame 读取我们的输入 CS 文件
dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesRecords.csv")
print("\nInput CSV file = \n", dataFrame)

# 根据 Car 列排序
dataFrame.sort_values("Car", axis=0, ascending=True,inplace=True, na_position='first')

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

# 根据 Reg_Price 列排序
dataFrame.sort_values("Reg_Price", axis=0, ascending=True,inplace=True, na_position='first')

print("\nSorted CSV file (according to Registration Price) = \n", dataFrame)

输出

这将产生以下输出

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

相关文章


有用资源