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输出结果# Create 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']
}
)
print"DataFrame ...\n",dataFrame
# Sort DataFrame in descending order according to the element frequency
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
以上是 Python Pandas - 根据元素频率降序对 DataFrame 进行排序 的全部内容, 来源链接: utcz.com/z/352652.html