sort_index按索引排序
import pandas as pd
data1 = {
"age": [16, 14, 10],
"qualified": [True, True, True]
}
df1 = pd.DataFrame(data1)
data2 = {
"age": [55, 40],
"qualified": [True, False]
}
df2 = pd.DataFrame(data2)
newdf = df1.append(df2)
print(newdf)
输出:
age qualified 0 16 True 1 14 True 2 10 True 0 55 True 1 40 False
newdf.sort_index(axis=1, inplace = True, ascending=True)
print(newdf)
常见参数
sort_index参数分axis,inplace, ascending
axis=0默认的,按行索引进行排序 ascending=True默认的,按索引的升序排列 inplace = False默认不改变原来的值 测试如下:
newdf.sort_index(inplace=True)
age qualified
0 16 True
0 55 True
1 14 True
1 40 False
2 10 True
newdf.sort_index(axis =1 , inplace=True)
对 'age' , 'qualified'进行按列索引升序排序
age qualified
0 16 True
1 14 True
2 10 True
0 55 True
1 40 False
newdf.sort_index(axis =1 , inplace=True, ascending=False)
对 'age' , 'qualified'进行按列索引降序排序
qualified age
0 True 16
1 True 14
2 True 10
0 True 55
1 False 40
sort_values按值排序
newdf.sort_values(by = ['age'], inplace= True)
print(newdf)
对'age'进行排序,默认axis=0
age qualified
2 10 True
1 14 True
0 16 True
1 40 False
0 55 True
—— 本文来自火龙信奥(义乌睿码科技):义乌青少年信息学奥赛与编程教育平台,专注 CSP-J/S、NOIP、GESP 竞赛培训,线上线下融合教学,助力编程升学。网址:hlcoding.com