Computer >> Máy Tính >  >> Lập trình >> Python

Làm cách nào để sắp xếp CSV theo nhiều cột trong Python?

Để sắp xếp CSV theo nhiều cột, hãy sử dụng phương thức sort_values ​​(). Sắp xếp theo nhiều cột có nghĩa là nếu một trong các cột có giá trị lặp lại thì thứ tự sắp xếp phụ thuộc vào 2 nd cột được đề cập trong phương thức sort_values ​​().

Đầu tiên, hãy để chúng tôi đọc tệp CSV đầu vào “SalesRecords.csv” -

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

Bây giờ chúng ta hãy sắp xếp theo nhiều cột, tức là “Reg_Price” và “Car” -

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

Ví dụ

Sau đây là mã -

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)

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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