Pandas DataFrame按照列的值排序
参考Pandas的官方文档:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html
输入:
col1 col2 col3
0 A 2 0
1 A 1 1
2 B 9 9
3 NaN 8 4
4 D 7 2
5 C 4 3
期望输出:
col1 col2 col3
4 D 7 2
5 C 4 3
2 B 9 9
0 A 2 0
1 A 1 1
3 NaN 8 4
Python 实现按 col1、col2 依次降序排序:
import numpy as np
import pandas as pd
# 产生数据
df = pd.DataFrame({'col1': ['A', 'A', 'B', np.nan, 'D', 'C'], 'col2': [2, 1, 9, 8, 7, 4], 'col3': [0, 1, 9, 4, 2, 3], })
# 功能实现
df.sort_values(by=['col1', 'col2'], ascending=False)
还没有评论,来说两句吧...