pandasgroupby按出现顺序排序
时间: 2023-10-23 14:14:40 浏览: 41
你可以使用 `pd.Categorical` 和 `sort_values` 来按照出现顺序排序进行分组,示例如下:
```
import pandas as pd
# 构造数据
df = pd.DataFrame({'fruit': ['apple', 'orange', 'banana', 'orange', 'banana', 'apple'],
'price': [3, 2, 4, 5, 8, 2]})
# 将 fruit 列转换为 Categorical 类型,并指定顺序
df['fruit'] = pd.Categorical(df['fruit'], categories=['apple', 'orange', 'banana'], ordered=True)
# 按 fruit 列进行分组,并按照 fruit 列的顺序排序
result = df.groupby('fruit').sum().sort_values('fruit')
print(result)
```
输出结果如下:
```
price
fruit
apple 5
orange 7
banana 12
```
其中,`pd.Categorical` 用于将 `df['fruit']` 转换为 Categorical 类型,并指定顺序。`df.groupby('fruit').sum()` 用于按照 fruit 列进行分组,并对 price 列进行求和。最后,`sort_values` 函数按照 fruit 列的顺序进行排序。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)