pandas 如何对groupby之后的对象进行排序
时间: 2023-05-26 16:06:42 浏览: 56
在 pandas 中,可以使用 `sort_values()` 方法对 groupby 后的对象进行排序。具体步骤如下:
首先定义一个 DataFrame:
```
import pandas as pd
df = pd.DataFrame({'A': ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'a'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': [1, 2, 3, 4, 5, 6, 7, 8],
'D': [10, 20, 30, 40, 50, 60, 70, 80]})
print(df)
```
输出结果为:
```
A B C D
0 a one 1 10
1 b one 2 20
2 a two 3 30
3 b three 4 40
4 a two 5 50
5 b two 6 60
6 a one 7 70
7 a three 8 80
```
然后对 A 、B 列进行分组并计算平均值,再对 A、B 以及平均值进行排序:
```
grouped_df = df.groupby(['A', 'B']).mean().reset_index()
sorted_df = grouped_df.sort_values(by=['A', 'B', 'C'], ascending=[True, True, False])
print(sorted_df)
```
输出结果为:
```
A B C D
0 a one 4 40
1 a three 8 80
2 a two 4 40
3 b one 2 20
4 b three 4 40
5 b two 6 60
```
其中,`by` 参数指定排序的列名,`ascending` 参数指定升序或降序。以上示例是按 A 列和 B 列升序排列,按 C 列降序排列。