zl程序教程

您现在的位置是:首页 >  .Net

当前栏目

Lesson10——Pandas sorting排序

2023-02-18 16:33:24 时间

pandas目录

1 简介

  Pands 提供了两种排序方法,分别是按标签排序和按数值排序。本节讲解 Pandas 的排序操作。

  下面创建一组 DataFrame 数据,如下所示:

df = pd.DataFrame({'b':[1,2,3,2],
                  'a':[4,3,2,1],
                   'c':[1,3,8,2],
                   'd':[2,0,1,3],
                  })
df
#输出结果:
     b    a    c    d
0    1    4    1    2
1    2    3    3    0
2    3    2    8    1
3    2    1    2    3

  上述示例,行标签和数值元素均未排序,下面分别使用标签排序、数值排序对其进行操作。

2 按标签排序

  使用 sort_index() 方法对行标签排序,指定轴参数(axis)或者排序顺序。或者可以对 DataFrame 进行排序。默认情况下,按照行标签序排序

Example:

print("原始数据为:")
print(df)
print("排序后的数据为:")
print(df.sort_index())
#输出结果:
原始数据为:
   b  a  c  d
0  1  4  1  2
1  2  3  3  0
2  3  2  8  1
3  2  1  2  3
排序后的数据为:
   b  a  c  d
0  1  4  1  2
1  2  3  3  0
2  3  2  8  1
3  2  1  2  3

2.1 排序顺序

  通过将布尔值传递给ascending参数,可以控制排序的顺序(行号顺序)。

Example:

print("1排序后的数据为:")
print(df.sort_index(ascending=False))
print("2排序后的数据为:")
print(df.sort_index(ascending=True))
#输出结果:
1排序后的数据为:
   b  a  c  d
3  2  1  2  3
2  3  2  8  1
1  2  3  3  0
0  1  4  1  2
2排序后的数据为:
   b  a  c  d
0  1  4  1  2
1  2  3  3  0
2  3  2  8  1
3  2  1  2  3

3 按列标签排序

  通过给  axis  轴参数传递 0 1,可以对列标签进行排序。默认情况下,axis=0 表示按行排序;而 axis=1 则表示按列排序。

Examples:

print(df.sort_index(ascending=True,axis =0))
#输出结果
   b  a  c  d
0  1  4  1  2
1  2  3  3  0
2  3  2  8  1
3  2  1  2  3

print(df.sort_index(ascending=True,axis =1))
#输出结果
   a  b  c  d
0  4  1  1  2
1  3  2  3  0
2  2  3  8  1
3  1  2  2  3

4 按值排序

  • sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')
  • 作用:既可以根据列数据,也可根据行数据排序。

Example:原始数据

df = pd.DataFrame({'b':[1,2,3,2],'a':[4,3,2,1],'c':[1,3,8,2]},index=[2,0,1,3]) 
df
#输出结果:
     b    a    c
2    1    4    1
0    2    3    3
1    3    2    8
3    2    1    2

Example: 按  b  列升序排序

df.sort_values(by='b') #等同于df.sort_values(by='b',axis=0)
#输出结果:
    b   a   c
2   1   4   1
0   2   3   3
3   2   1   2
1   3   2   8

Example: 先按 b 列降序,再按 a 列升序排序

df.sort_values(by=['b','a'],axis=0,ascending=[False,True]) #等同于df.sort_values(by=['b','a'],axis=0,ascending=[False,True]) 
#输出结果
1   3   2   8
3   2   1   2
0   2   3   3
2   1   4   1

Example: 按行 3 升序排列

df.sort_values(by=3,axis=1) #必须指定axis=1
#输出结果:
    a   b   c
2   4   1   1
0   3   2   3
1   2   3   8
3   1   2   2

Example: 按行3升序,行0降排列

df.sort_values(by=[3,0],axis=1,ascending=[True,False])
#输出结果:
     a   c   b
2   4   1   1
0   3   3   2
1   2   8   3
3   1   2   2

5 排序算法

  sort_values() 提供了参数 kind 用来指定排序算法。这里有三种排序算法:

  • mergesort
  • heapsort
  • quicksort

  默认为 quicksort(快速排序) ,其中 Mergesort 归并排序是最稳定的算法。

Example: 

print("原始数据为:")
print(df)
print("排序5后的数据为:")
print(df.sort_values(ascending=False,by='b',kind='mergesort'))
#输出结果
原始数据为:
   b  a  c
2  1  4  1
0  2  3  3
1  3  2  8
3  2  1  2
排序5后的数据为:
   b  a  c
1  3  2  8
0  2  3  3
3  2  1  2
2  1  4  1