Python 如何对多索引数据帧中的值进行排序?

Python 如何对多索引数据帧中的值进行排序?,python,pandas,Python,Pandas,我有一个多索引的熊猫数据帧。我想对列的值进行排序,并比较索引level0中的值。如果该值为最大值,则id应为1,如果该值为次值,则id应为2。最后,输出其排序id 例如: arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo','foo', 'foo','qux', 'qux'], ['one', 'two', 'three','one', 'two', 'one', 'two','three', 'four', 'one

我有一个多索引的熊猫数据帧。我想对列的值进行排序,并比较索引level0中的值。如果该值为最大值,则id应为1,如果该值为次值,则id应为2。最后,输出其排序id

例如:

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
输出:

            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
最后,我想说:

            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

按第一级即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

你的意思是:作为旁注,您可能希望避免命名列“values”:它已经是一个允许您访问底层NumPy数组的属性。您可能还希望在使用np.random时提供种子,以便其他人可以轻松地重新创建您的数据帧值。谢谢,@BradSolomonGREAT…但有一点是,当两个值相同时,输出将为。5。为什么?有不同的方法可以产生不同的行为。看看我在问题中提供的链接文档。这些方法是平均值,这是默认值以及最小值、最大值、第一值和密集值。