python - 对包含 str 和元组的 Pandas MultiIndex 进行排序
问题描述
所以我有一个带有多级多索引的数据框,其中较小的索引是父级,添加一级索引会创建看起来像这样的子级
(a,foo,1)
(a,foo,2)
(a,foo)
a
(b, foo,1)
(b, bar,1)
(b, foo)
(b, bar)
b
我想对索引进行排序,但是在使用 sort_index 函数时收到以下错误,
TypeError: '<' not supported between instances of 'str' and 'tuple'
由于任何大于 1 级的索引都存储为元组,而单个索引存储为字符串,我无法对索引进行排序。
让我的索引成为单一数据类型以便对它进行排序的最佳方法是什么?
a
(a,foo)
(a,foo,1)
(a,foo,2)
b
(b, bar)
(b, bar,1)
(b, foo)
(b, foo,1)
解决方案
sort_values
让我们尝试一起爆炸na_position
l = df.index
s = pd.DataFrame(l).sort_values([0,1,2],na_position='first').index
df = df.iloc[s]
推荐阅读
- css - 限制下载按钮,只有登录用户才能查看按钮
- mysql - MYSQL 中的 date_trunc('minute', timestamp) 等价物
- npm - 无法使用“=”登录 cross-env-shell
- python-3.x - Python 异步 Websocket 方法返回 Future
- python - 我正在尝试创建一个猜数游戏,但是当我运行它时,它会继续运行 while 循环并且不会中断
- flutter - 对 BorderRadius 感到困惑
- structure - Visual Studio 中的维度结构选项卡在哪里?
- communication - 如何为非 subnero 调制解调器编写调制解调器驱动程序?
- windows - 使用 for 循环列出所有 mp4 文件并选择一个
- javascript - 如何从客户端获取firebase存储json文件