Để sắp xếp CSV theo nhiều cột, dùng phương thức sort_values(). Sắp xếp nhiều cột nghĩa là nếu cột đầu có giá trị trùng, thứ tự phụ thuộc vào cột thứ hai.
Đọc file SalesRecords.csv:
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv") Sắp xếp theo nhiều cột "Reg_Price" và "Car":
dataFrame.sort_values(["Reg_Price","Car"], axis=0, ascending=True, inplace=True, na_position='first')
Ví dụ
import pandas as pd
# Đọc file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
print("\nFile CSV gốc = \n", dataFrame)
# Sắp xếp nhiều cột
dataFrame.sort_values(["Reg_Price","Car"], axis=0, ascending=True, inplace=True, na_position='first')
print("\nFile CSV đã sắp xếp (theo nhiều cột) = \n", dataFrame) Kết quả
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