python - 为每个级别对 Pandas 中的多索引进行不同的排序
问题描述
我有一个索引为 3 级的数据框。我需要按每个级别对索引进行排序,但方式不同。有什么可以做到这一点?
有一个数据框 ( df
) 为:
other columns
color shape count
red circle 1 x
triangle 3 x
2 x
blue circle 4 x
triangle 2 x
我想要一个新的df
where color
is sorted ascending
, shape
isdescending
和count
is ascending
:
other columns
color shape count
blue triangle 2 x
circle 4 x
red triangle 2 x
3 x
circle 1 x
解决方案
将ascending
参数与布尔值列表一起使用:
df.sort_index(ascending=[True, False, True])
输出:
other columns
color shape count
blue triangle 2 x
circle 4 x
red triangle 2 x
3 x
circle 1 x
推荐阅读
- ios - UINavigationBar tintColor 行为不端
- python - 如何使对象在pygame中移动,而不会使渲染变慢?
- c# - 未找到与请求 URI 匹配的 HTTP 资源,未在控制器上找到任何操作
- angular - 将 http 请求结果与 Array 合并
- memory-management - Cython 更新对象属性
- r - 如何在 R 的 list() 中创建矩阵
- mysql - 一个疯狂的数据库结构 - 建议
- amazon-sagemaker - 访问 Crowd HTML 输出结果
- hibernate - 面对错误 TranManagerSet 与 Websphere 8.5 上的 TransactionManager 不兼容。创建休眠搜索索引
- bash - bash脚本,想要使用'$'而不寻找变量