Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách sắp xếp CSV theo một cột trong Python?

Để sắp xếp CSV theo một cột, sử dụng phương thức sort_values(). Đặt cột bạn muốn sắp xếp trong sort_values().

Trước tiên, đọc file CSV "SalesRecords.csv" với DataFrame:

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

Sắp xếp theo cột "Car":

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

Tiếp theo, sắp xếp theo cột "Reg_Price":

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

Ví dụ hoàn chỉnh

Mã nguồn đầy đủ:

import pandas as pd
# DataFrame đọc file CSV đầu vào
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
print("\nFile CSV đầu vào = \n", dataFrame)
# sắp xếp theo cột Car
dataFrame.sort_values("Car", axis=0, ascending=True, inplace=True, na_position='first')
print("\nFile CSV đã sắp xếp (theo tên xe) = \n", dataFrame)
# sắp xếp theo cột Reg_Price
dataFrame.sort_values("Reg_Price", axis=0, ascending=True, inplace=True, na_position='first')
print("\nFile CSV đã sắp xếp (theo giá đăng ký) = \n", dataFrame)

Kết quả

Chương trình sẽ tạo ra kết quả sau:

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