所以我有一个带有多级多索引的数据框,其中较小的索引是父索引,添加一个索引级别会创建看起来像这样的子元素
(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)
最佳答案
让我们尝试在行中展开,然后使用na_position
sort_values
l = df.index
s = pd.DataFrame(l).sort_values([0,1,2],na_position='first').index
df = df.iloc[s]
https://stackoverflow.com/questions/63570491/
相关文章:
git - 以编程方式为新的 Azure 存储库设置默认分支名称
java - 无法在 Linux 上的 Intellij 中指定 SDK
java - 无法在数据库中使用 BCryptPassword 保存加密密码
c# - 如何从 .NET Core 3.1 中的 DI 获取 SignalR IHubContex
php - 带有 "sometimes"规则的 Laravel Validator 自定义消息
amazon-web-services - AWS API 网关上的剥离 header
python - 如何启用对 Dash DataTable 上特定行的编辑