Python Pandas - 根据元素频率降序对 DataFrame 进行排序
要按升序或降序对数据进行排序,请使用sort_values()method。对于降序,在sort_values()方法中使用以下内容-
ascending=False
导入所需的库-
import pandas as pd
创建一个包含3列的DataFrame-
dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000],"Place": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh'] } )
要根据元素频率按降序对DataFrame进行排序,我们需要对出现次数进行计数。因此,count()也与sort_values()set一起用于降序排序-
dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False)
示例
以下是代码-
import pandas as pd #CreateDataFrame dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000],"Place": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh'] } ) print"DataFrame ...\n",dataFrame #SortDataFrameindescendingorderaccordingtotheelementfrequency dataFrame = dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False) print"\nSorting DataFrame ...\n",dataFrame输出结果
这将产生以下输出-
DataFrame ... Car Place Reg_Price 0 BMW Pune 7000 1 Lexus Delhi 1500 2 BMW Mumbai 5000 3 Mustang Hyderabad 8000 4 Mercedes Bangalore 9000 5 Lexus Chandigarh 2000 Sorting DataFrame ... Car Count 0 BMW 2 1 Lexus 2 2 Mercedes 1 3 Mustang 1