Python Pandas - 根据元素频率按升序对 DataFrame 进行排序
要按升序或降序对数据进行排序,请使用sort_values()method。对于升序,使用以下sort_values()方法-
ascending=True
导入所需的库-
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=True)
示例
以下是代码-
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 #SortDataFrameinascendingorderaccordingtotheelementfrequency dataFrame = dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=True) print"\nSorting DataFrame in ascending order ...\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 in ascending order ... Car Count 2 Mercedes 1 3 Mustang 1 0 BMW 2 1 Lexus 2