数据排序&pandas

工具:jupyter Python3

数据排序

import numpy as np
import pandas as pd

参数说明:
1、axis:轴索引(排序的方向),0代表index(行),1代表columns(列)
2、ascending:是否升序排序,默认为True,表示升序,降序(False)
3、by:表示排序的列(按值进行排序)

更多参数详见:https://pandas.pydata.org/docs/user_guide/dsintro.html#dataframe

DataFrame行列排序

1、一个DataFrame对象,5行3列,随机整数,范围0-9,行索引为3,4,6,8,5,按照行索引降序排列

df1 = pd.DataFrame(np.random.randint(0,10,(5,3)),index=[3,4,6,8,5])
df1
0 1 2
3 5 5 9
4 8 4 1
6 4 8 6
8 8 4 0
5 0 3 8
#按照行索引降序排序
df1.sort_index(axis=0,ascending=False)
0 1 2
3 5 5 9
4 8 4 1
5 0 3 8
6 4 8 6
8 8 4 0

2、一个DataFrame对象,5行5列,随机整数,范围0-9,列索引为3,1,7,9,6,按照列索引降序排列

df2 = pd.DataFrame(np.random.randint(0,10,(5,5)),columns=[3,1,7,9,6])
df2
3 1 7 9 6
0 2 0 1 1 8
1 8 6 5 8 0
2 5 6 1 9 9
3 3 3 2 9 4
4 9 1 6 0 4
df2.sort_index(axis=1,ascending=False)
1 3 6 7 9
0 0 2 8 1 1
1 6 8 0 5 8
2 6 5 9 1 9
3 3 3 4 2 9
4 1 9 4 6 0

3、一个DataFrame对象,5行3列,随机整数,范围0-9,按照第二列的值降序排序

df3 = pd.DataFrame(np.random.randint(0,9,(5,3)))
df3
0 1 2
0 4 7 4
1 8 3 2
2 7 3 2
3 0 6 3
4 0 4 6
df3.sort_values(by=1,ascending=False)
0 1 2
0 4 7 4
3 0 6 3
4 0 4 6
1 8 3 2
2 7 3 2

4、一个DataFrame对象,5行3列,随机整数,范围0-9,按照第一行值升序排序

df4 = pd.DataFrame(np.random.randint(0,9,(5,3)))
df4
0 1 2
0 3 5 0
1 3 1 1
2 0 4 8
3 6 7 6
4 5 4 7
df4.sort_values(axis=1,by=0)
2 0 1
0 0 3 5
1 1 3 1
2 8 0 4
3 6 6 7
4 7 5 4

Series索引、值排序

一个Series对象,随机整数,范围0-10,长度为6

ser1 = pd.Series(np.random.randint(0,10,6))
ser1
0    5
1    5
2    0
3    3
4    8
5    2
dtype: int32

1、按照索引升序进行排序

ser1.sort_index()
0    5
1    5
2    0
3    3
4    8
5    2
dtype: int32

2、按照值进行降序排序

ser1.sort_values(ascending=False)
4    8
1    5
0    5
3    3
5    2
2    0
dtype: int32

注意:
1)ascending等号后面不要加引号
2)注意按索引排序时,是指索引的轴,默认为0(代表行的索引),1(代表列的索引),但其本质还是对相应轴的数据进行排序(详细看上边例题)
如:按索引进行排序时,当axis=0时,表示按照行的索引进行排序,本质上就是对值的排序。
3)当对象调用sort_values进行排序时,所有的缺失值默认都会放到末尾。(这里可以使用参数:na_position,他的值为first,last,顾名思义若na_position= 'first’时则会讲NaN值放到开头,后者反之。)

猜你喜欢

转载自blog.csdn.net/m0_46202060/article/details/115305289