dataframe 按照多列排序
时间: 2023-11-09 17:05:27 浏览: 155
要按多列排序一个 pandas 的 DataFrame,你可以使用 sort_values 函数。下面是一个例子:
``` python
import pandas as pd
# 创建一个 DataFrame
df = pd.DataFrame({'A': ['a', 'b', 'c', 'a', 'b', 'c'],
'B': [3, 2, 1, 6, 5, 4],
'C': [1, 4, 2, 5, 3, 6]})
# 按照 A 列和 B 列排序,优先按照 A 列排序,A 列相同时再按照 B 列排序
df_sorted = df.sort_values(['A', 'B'])
print(df_sorted)
```
这将输出以下 DataFrame:
```
A B C
0 a 3 1
3 a 6 5
1 b 2 4
4 b 5 3
2 c 1 2
5 c 4 6
```
如果想要按照不同的列有不同的排序方式,可以在排序时为每个列指定排序方式,例如:
``` python
# 按照 A 列升序,B 列降序排序
df_sorted = df.sort_values(['A', 'B'], ascending=[True, False])
```
这将输出以下 DataFrame:
```
A B C
0 a 3 1
3 a 6 5
4 b 5 3
1 b 2 4
5 c 4 6
2 c 1 2
```
阅读全文
相关推荐















