python - 对组内的值进行排序
问题描述
假设我有这个数据框:
df = pd.DataFrame({
'price': [2, 13, 24, 15, 11, 44],
'category': ["shirts", "pants", "shirts", "tops", "hat", "tops"],
})
price category
0 2 shirts
1 13 pants
2 24 shirts
3 15 tops
4 11 hat
5 44 tops
我想以这样的方式对值进行排序:
- 找出每个类别的最高价格是多少。
- 根据最高价格对类别进行排序(在本例中,按降序排列:上衣、衬衫、裤子、帽子)。
- 根据较高的价格对每个类别进行排序。
最终的数据框如下所示:
price category
0 44 tops
1 15 tops
2 24 shirts
3 24 shirts
4 13 pants
5 11 hat
解决方案
我不是单线的忠实粉丝,所以这是我的解决方案:
# Add column with max-price for each category
df = df.merge(df.groupby('category')['price'].max().rename('max_cat_price'),
left_on='category', right_index=True)
# Sort
df.sort_values(['category','price','max_cat_price'], ascending=False)
# Drop column that has max-price for each category
df.drop('max_cat_price', axis=1, inplace=True)
print(df)
price category
5 44 tops
3 15 tops
2 24 shirts
0 2 shirts
1 13 pants
4 11 hat
推荐阅读
- resources - 当 URL 未出现在源代码中时,如何避免错误请求?
- html - 如何旋转外部div而不是内部内容
- php - 如何修复 'Illuminate \ Database \ Eloquent \ MassAssignmentException' 上的 _token 错误
- reactjs - React- Webpack 缩小代码并在开发环境中创建包。我想要 dev 中的所有未捆绑的文件,以便我可以调试
- java - ListView 不使用自定义视图更新大小
- xml - XML 文件输出失败
- python-3.x - 通过python将文件作为输入传递给shell脚本
- sql-server - 搜索模式的查询性能
- java - 如何在 Rest Assured POST 方法中执行 NTLM 身份验证?
- javascript - 如何在 Vue.JS 中使用 axios 方法填充组件的数据