pandas 排序之 sort_index

                                                                排序之 sort_index

 

sort_index 对行或列索引进行排序。

Series 的 sort_index(ascending=True) 方法可以对 index 进行排序操作,ascending 参数用于控制升序或降序,默认为升序。

在 DataFrame 上,.sort_index(axis=0, ascending=True) 方法多了一个轴向的选择参数。

import numpy as np

# sort_index() 索引排序
ser1 = pd.Series(np.random.randint(0, 101, 5), index=list("EBACD"))
ser1
# 运行结果:
E    31
B    78
A    95
C     6
D    93
dtype: int32

# 通过列或者行索引进行排序
ser1.sort_index()
# 运行结果:
A     41
B     65
C    100
D     18
E     51
dtype: int32

# 倒序,由大到小
ser1.sort_index(ascending=False)
# 运行结果:
E    73
D     9
C     5
B    85
A    95
dtype: int32

df1 = pd.DataFrame(np.random.randint(0, 101, [5, 3]), index=list("EBACD"), columns=list("xzy"))
df1
# 运行结果:
    x	z	y
E	71	42	51
B	54	63	49
A	65	94	98
C	97	95	68
D	32	79	41

# 通过行索引排序
df1.sort_index()
# 运行结果:
	x	z	y
A	26	73	52
B	29	22	73
C	96	23	65
D	75	52	72
E	27	57	29

# 通过列索引进行排序
df1.sort_index(axis=1)
# 运行结果:
	x	y	z
E	60	6	40
B	71	41	8
A	62	92	15
C	56	49	57
D	7	56	59

# 通过列索引进行排序,降序
df1.sort_index(axis=1, ascending=False)
# 运行结果:
	z	y	x
E	79	29	87
B	27	40	88
A	54	74	49
C	94	29	41
D	96	54	53

df1.sort_index(axis="index").sort_index(axis="columns")
# 运行结果:
	x	y	z
A	27	9	68
B	79	75	43
C	33	9	89
D	82	89	40
E	88	83	57

 

你可能感兴趣的:(pandas 排序之 sort_index)