Pandas 支持三种排序方式,按索引标签排序,按列里的值排序,按两种方式混合排序。
按值排序:sort_values()
- Series.sort_values() 方法用于按值对 Series 排序。
- DataFrame.sort_values() 方法用于按行列的值对 DataFrame 排序。
df 相关参数:
- by :行名/列名 多字段排序时 by =[‘字段一’, ‘字段二’])
- axis :默认按列排序。如果axis=0,那么by=”列名”; 如果axis=1,那么by=”行名”;
- ascending: True/False,默认True。多字段排序时可以是[True,False],即第一字段升序,第二个降序
- inplace:True/False。 是否在原有数据上进行修改 。
- 当 inplace = False 时,返回为修改过的数据,原数据不变。
- 当 inplace = True 时,返回值为 None,直接在原数据上进行操作。
- kind: 排序方法
- na_position : {‘first’, ‘last’}, default ‘last’,默认缺失值排在最后面
相关示例
参数: inplace
df = pd.DataFrame(np.arange(8).reshape(4, 2))
print(df)
print("*"*20)
df.sort_values(by=1, ascending=False, inplace=False)
print(df)
print("*"*20)
df.sort_values(by=1, ascending=False, inplace=True)
print(df)
输出:
0 1
0 0 1
1 2 3
2 4 5
3 6 7
********************
0 1
0 0 1
1 2 3
2 4 5
3 6 7
********************
0 1
3 6 7
2 4 5
1 2 3
0 0 1
参数:axis、by、ascending
df = pd.DataFrame(np.arange(8).reshape(4, 2))
print(df)
print("*"*20)
df.sort_values(by=1, ascending=False, inplace=True)
print(df)
print("*"*20)
df.sort_values(by=2, axis=1, ascending=False, inplace=True)
print(df)
输出:
0 1
0 0 1
1 2 3
2 4 5
3 6 7
********************
0 1
3 6 7
2 4 5
1 2 3
0 0 1
********************
1 0
3 7 6
2 5 4
1 3 2
0 1 0
按索引排序:sort_index()
Series.sort_index()与 DataFrame.sort_index() 方法用于按索引层级对 Pandas 对象排序。
相关参数
- axis:
- level:默认None,
- ascending:默认True
- inplace:默认False
- kind:
- na_position:
- by:
df = pd.DataFrame(np.arange(6).reshape(3, 2))
print(df)
print("*"*20)
df.sort_index(ascending=False, axis=1, inplace=True)
print(df)
df.sort_index(ascending=False, axis=0, inplace=True)
print(df)
0 1
0 0 1
1 2 3
2 4 5
********************
1 0
0 1 0
1 3 2
2 5 4
1 0
2 5 4
1 3 2
0 1 0
nan值和多列排序
df = pd.DataFrame(np.array([[1, 4, 2, 3, ], [3, 2, np.nan, 6], [0, 2, 2, 4]]))
print(df)
df.sort_values(by=[1, 3], ascending=[False, True], inplace=True,)
print(df)
df.sort_values(by=2, na_position='first', inplace=True,)
print(df)
输出
0 1 2 3
0 1.0 4.0 2.0 3.0
1 3.0 2.0 NaN 6.0
2 0.0 2.0 2.0 4.0
0 1 2 3
0 1.0 4.0 2.0 3.0
2 0.0 2.0 2.0 4.0
1 3.0 2.0 NaN 6.0
0 1 2 3
1 3.0 2.0 NaN 6.0
0 1.0 4.0 2.0 3.0
2 0.0 2.0 2.0 4.0
Original: https://blog.csdn.net/qq_40926887/article/details/124225665
Author: 捌椒
Title: 数据分析之pandas数据排列【sort_values()、sort_index()】
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/599732/
转载文章受原作者版权保护。转载请注明原作者出处!