我有一个带有MultiIndex的pandas DataFrame。我想对一列的值进行排序,并比较索引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 :(得分:1)
在第一级(即0级)上分组,然后按降序rank分组。
>>> 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