如何在 Python 中按多列对 CSV 进行排序?
要按多列对CSV进行排序,请使用sort_values()方法。按多列排序意味着如果其中一列具有重复值,则排序顺序取决于方法中提到的第二列sort_values()。
首先,让我们阅读我们的输入CSV文件“SalesRecords.csv”-
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
现在让我们根据多列进行排序,即“Reg_Price”和“Car”-
dataFrame.sort_values(["Reg_Price","Car"],axis=0, ascending=True,inplace=True,na_position='first')
示例
以下是代码-
import pandas as pd #DataFrametoreadourinputCSfile dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv") print("\nInput CSV file = \n", dataFrame) #sortingaccordingtomultiplecolumns 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)输出结果
这将产生以下输出-
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