简体   繁体   English

如何对MultiIndex Pandas数据框中的值进行排序?

[英]How to sort values in a MultiIndex pandas dataframe?

I have a pandas DataFrame with MultiIndex. 我有一个带有MultiIndex的pandas DataFrame。 I want to sort the values of a column, and compare values in index level0. 我想对一列的值进行排序,并比较索引level0中的值。 If the value is the maximum, the id should be 1, and if the value is the secondary, the id should be 2. Finally, output its sorted id. 如果值是最大值,则id应该为1,如果值是次要,则id应该为2。最后,输出其排序的id。

For example: 例如:

arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo','foo', 'foo','qux', 'qux'],
      ['one', 'two', 'three','one', 'two', 'one', 'two','three', 'four',  'one', 'two']]
df = pd.DataFrame(np.random.randn(11), index=arrays,columns=['values'])
df

output: 输出:

            values
bar one     -1.098567
    two     -0.936011
    three   -0.654245
baz one     -0.637409
    two     -0.439939
foo one      0.238114
    two      1.146573
    three   -0.512294
    four    -0.611913
qux one     -0.481083
    two      0.515961

Finally, I want this: 最后,我想要这个:

            values      sort
bar one     -1.098567      3
    two     -0.936011      2
    three   -0.654245      1
baz one     -0.637409      2
    two     -0.439939      1
foo one      0.238114      2
    two      1.146573      1
    three   -0.512294      3
    four    -0.611913      4
qux one     -0.481083      2
    two      0.515961      1

Group on the first level (ie level 0), and then rank them in descending order. 组在所述第一水平(即0级),然后排列它们以降序。

>>> df.assign(sort=df.groupby(level=0).rank(ascending=False))
             values  sort
bar one   -1.098567     3
    two   -0.936011     2
    three -0.654245     1
baz one   -0.637409     2
    two   -0.439939     1
foo one    0.238113     2
    two    1.146573     1
    three -0.512295     3
    four  -0.611913     4
qux one   -0.481083     2
    two    0.515961     1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM