【问题标题】:how to sort a multi-level pandas data-frame by a particular column?如何按特定列对多级熊猫数据框进行排序?
【发布时间】:2020-06-07 17:59:35
【问题描述】:

我想按列对多索引 pandas 数据框进行排序,但不希望一次对整个数据框进行排序。而是想按索引之一进行排序。这是我的意思的一个例子:下面是一个多索引数据框的例子。

first  second
bar    one       0.361041
       two       0.476720
baz    one       0.565781
       two       0.848519
foo    one       0.405524
       two       0.882497
qux    one       0.488229
       two       0.303862

而我想要的是:

first  second
bar    two       0.476720
       one       0.361041
baz    two       0.848519
       one       0.565781
foo    two       0.882497
       one       0.405524
qux    two       0.488229
       one       0.303862

我想根据第三列(即数字)对数据框进行排序,并保持 0 级索引不变。我们该怎么做?

【问题讨论】:

  • 我无法理解您的问题。你能澄清一下吗?

标签: python pandas


【解决方案1】:

Series.reindex 与已排序的二级值一起使用:

a = s.reindex(sorted(s.index.levels[1], reverse=True), level=1)
print (a)
first  second
bar    two       0.476720
       one       0.361041
baz    two       0.848519
       one       0.565781
foo    two       0.882497
       one       0.405524
qux    two       0.303862
       one       0.488229
Name: a, dtype: float64

【讨论】:

  • s.loc[('qux','three')]=1.03490 将重新索引添加three 到每个组?
  • @Ch3steR - 你是对的,已根据要求编辑答案
  • s.reindex(['two','three','one','four'], level=1) 我试图像这样重新索引,但 'three''four' 并未添加到每个组中。它应该添加正确并填充 NaN 对吗?
  • @Ch3steR - 嗯,对我来说工作正常,s.loc[('qux','three')]=1.03490
  • stackoverflow.com/questions/62214123/… 这就是我所说的。
【解决方案2】:

您可以使用sort index 对索引进行排序,并将[True,False] 的布尔值传递给ascending 参数

df.sort_index(level=[0,1],ascending=[True,False])

                Unnamed: 2
first   second  
bar      two    0.476720
         one    0.361041
baz      two    0.848519
         one    0.565781
foo      two    0.882497
         one    0.405524
qux      two    0.303862
         one    0.488229

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多