【问题标题】:How to sort the indices of a pandas multi-index data frame according to a custom order如何根据自定义顺序对 pandas 多索引数据框的索引进行排序
【发布时间】:2021-10-03 15:54:57
【问题描述】:

以下是生成示例数据框的一些代码:

fruits=pd.DataFrame()
fruits['month']=['jan','feb','feb','march','jan','april','april','june','march','march','june','april']
ind_mnth=fruits['month'].values
fruits['fruit']=['apple','orange','pear','orange','apple','pear','cherry','pear','orange','cherry','apple','cherry']
ind_fruit=fruits['fruit'].values
fruits['price']=[30,20,40,25,30 ,45,60,45,25,55,37,60]
fruits_grp = fruits.set_index([ind_mnth, ind_fruit],drop=False)

如何对这个多索引数据框的行进行排序,使得每个外部索引(月)下的内部索引(水果)按照自定义顺序排序,具有相同外部索引的行组合在一起。

【问题讨论】:

    标签: pandas dataframe multi-index


    【解决方案1】:

    一种方法是创建一个categorical 系列水果列,其顺序为您想要的,然后set_index 与每个级别的Multiindex.from_arrays,和sort_index 就像您所做的那样

    # custom order
    ord_fruit = ['apple', 'pear', 'cherry', 'orange']
    # create a ordered Categorical series for the fruits
    f = pd.Categorical(fruits['fruit'], categories=ord_fruit, ordered=True)
    
    # get month values, could also be a custom order same idea than above
    m = fruits['month'].to_numpy()
    
    # get the result
    fruits_grp = fruits.set_index(pd.MultiIndex.from_arrays([m,f])).sort_index()
    print(fruits_grp)
                  month   fruit  price
    april pear    april    pear     45 # pear before cherry
          cherry  april  cherry     60
          cherry  april  cherry     60
    feb   pear      feb    pear     40
          orange    feb  orange     20
    jan   apple     jan   apple     30
          apple     jan   apple     30
    june  apple    june   apple     37
          pear     june    pear     45
    march cherry  march  cherry     55 # cherry before orange
          orange  march  orange     25
          orange  march  orange     25
    

    请注意,sort_index 将按字母顺序对其他级别进行排序,如果您不希望这样,您可以为每个级别创建自己的顺序。

    【讨论】:

    • 非常感谢!另外,是否可以随机顺序打乱月份,其余条件不变,即每个外部索引(月份)下的内部索引(水果)按照自定义顺序排序,具有相同外部索引的行分组在一起.换句话说,外部索引(月)应该以随机顺序打乱。
    • @MedhaChippa 一种方法是为月份创建一个分类系列,但顺序随机,这是 m 的一个想法:m = pd.Categorical(fruits['month'], categories=fruits['month'].sample(frac=1).unique(), ordered=True)。它们有很多方法可以创建类别以随机排列月份,但fruits['month'].sample(frac=1).unique() 就是其中之一
    猜你喜欢
    • 1970-01-01
    • 2017-01-12
    • 2018-07-08
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 2020-06-18
    • 2019-10-24
    相关资源
    最近更新 更多