【问题标题】:Index sort order of a multi-index dataframe does not respect categorical index order多索引数据帧的索引排序顺序不尊重分类索引顺序
【发布时间】:2018-08-25 09:06:07
【问题描述】:

具有两级多索引和一列的小型数据框。索引的第二列(级别 1)将按字母顺序排序,将“四”放在“三”之前。

import pandas as pd
df = pd.DataFrame({'A':[1,1,2,2],
  'B':['One','Two','Three', 'Four'], 
  'X':[1,2,3,4]},
  index=range(4)).set_index(['A','B']).sort_index()
df

         X
A B       
1 One    1
  Two    2
2 Four   4
  Three  3

显然第二级索引 (B) 是按字母顺序排列的,因此可以将其替换为分类索引以强制正确排序。

df.index.set_levels(pd.CategoricalIndex(df.index.levels[1], 
       categories=['One','Two','Three', 'Four'], ordered=True), 
    level=1, inplace=True)

完成后,检查索引显示级别 1 确实是一个分类索引。但是对索引进行排序不会将行按所需的顺序排列。

df.sort_index()

         X
A B       
1 One    1
  Two    2
2 Four   4
  Three  3

注意:如果数据框的简单索引为 1 级,则只有这可以按预期工作。

【问题讨论】:

  • 如果你指定创建数据框的顺序,你可以不使用sort_index吗?

标签: python pandas


【解决方案1】:

我设法通过在创建数据框后设置索引来得到这个 - 不确定这是否是最佳答案,但它是一个答案:

df = pd.DataFrame({'A':[1,1,2,2],
   'B':['One','Two','Three', 'Four'], 
   'X':[1,2,3,4]})
df = df.set_index(['A', pd.CategoricalIndex(df['B'], categories=['One','Two','Three', 'Four'], ordered=True)])
del df['B']

【讨论】:

  • 感谢您的努力。它创建的 CategoricalIndex 存在差异,不完全确定这种差异意味着什么,但它确实有效。
猜你喜欢
  • 2017-06-17
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
  • 2010-12-22
  • 1970-01-01
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多