我试图对一个数据帧进行分组,同时按某一列的绝对值对其进行排序。在groups values foo bar
75 A 3 1 2
77 B -3 31 34
112 A 4 0 4
129 C 50 5 3
134 C -60 44 5
在整个数据帧上我可以使用
^{pr2}$
这个很好用。但是,对于分组数据帧,这显然行不通。在
当我尝试的时候df.groupby('groups')['values'].reindex(df.values.abs().sort_values(ascending=False).index)
我得到了预期的错误:AttributeError: Cannot access callable attribute 'reindex' of 'SeriesGroupBy' objects, try using the 'apply' method
尝试apply可能需要为绝对值创建另一列,但我不想添加此列。有没有一个简洁的方法来实现这一点?在
所需的输出将是一个分组的数据帧(对象),按“值”列进行排序:for groups, data in df_grouped:
print group, data
A,
values foo bar
75 3 1 2
112 4 0 4
B,
values foo bar
77 -3 31 34
C,
values foo bar
134 -60 44 5
129 50 5 3