pandas Series和DataFrame的排序与排名
排序和排名是数据处理和分析中常用的方法 ,那么如何使用 pandas 进行数据的排序和排名呢,本节教程就来详细介绍。
【例 1 】定义一个 Series 对象 se 和一个 DataFrame 对象 df,编写一个程序分别实现对 se 和 df 的按索引排序和按值排序。
其代码 test1.py 如下。
① 默认情况下排名
其示例代码如下。
rank() 函数中有一个 method 参数,method 参数的选项见表 2。
② 按降序进行排名
其示例代码如下。
排序
在数据分析时,对数据排序是常用的一种操作,因此,pandas 提供了根据索引的大小或者值的大小对 Series 和 DataFrame 进行排序的函数,见表 1。函数 | 功能 |
---|---|
obj.sort_index(aixs,ascending) | 将 obj 按行或列的索引进行排序。参数:axis 可以赋值为 0 或 1,默认为 0,表示指定对行或列的索引排序;ascending 可以赋值 True 或 False,默认为 True,表示是升序排序,还是降序排序 |
obj.sort_values(by,aixs) | 将 obj 按指定行或列的值进行排序。参数:by 指定行或列,axis 可以 赋值为 0 或 1,表示指定对行或列的索引排序 |
注意:obj 为 Series 或 DataFrame 对象。
【例 1 】定义一个 Series 对象 se 和一个 DataFrame 对象 df,编写一个程序分别实现对 se 和 df 的按索引排序和按值排序。
其代码 test1.py 如下。
# -*- coding: utf-8 -*- import numpy as np from pandas import DataFrame, Series #Series按索引排序 se = Series([1,np.nan,5,7,0],index=['a','c','e','b','d']) #对Series的索引进行排序,默认是升序 print(se.sort_index()) #对索引进行降序排序 print(se.sort_index(ascending=False)) #对Series的值进行排序,默认是按值的升序进行排序 print(se.sort_values()) #对Seires的值进行降序排序 print(se.sort_values(ascending=False)) #对DataFrame按索引排序 a = np.array([[2,5,7],[1,0,3]]) df = DataFrame(a,index=['0','1'],columns=['b','c','a']) #按行的索引升序进行排序,默认为升序 print(df.sort_index()) #按行的索引降序进行排序 print(df.sort_index(ascending=False)) #按列的索引升序进行排序 print(df.sort_index(axis=1)) #按列的索引降序进行排序 print(df.sort_index(axis=1,ascending=False)) #按指定列的值进行排序 print(df.sort_values(by=['c','a'])) #按指定行的值进行排序 print(df.sort_values(by='1', axis=1))
排名
排名和排序有些类似,排名会为序列的每个元素安排一个初始值为 1、依次加 1 的位次,位次越靠前,所使用的数据越小,通过 rank() 函数可计算排名的位次。1) Series 的排名
使用 rank() 函数计算排名的位次。rank() 函数表示序列中的每个元素在原来的 Series 中排第几位(初始值为 1,依次加 1),若有相同的数,默认情况下取其排名的平均值。① 默认情况下排名
其示例代码如下。
In [17]: se = pd.Series([1,-1,0,1,2]) In [18]: se.rank() Out[18]: 0 3.5 1 1.0 2 2.0 3 3.5 4 5.0 dtype: float64
rank() 函数中有一个 method 参数,method 参数的选项见表 2。
参数 | 说明 |
---|---|
average | 默认值,即在相等分组中,为各值分配平均排名 |
min | 使用整个分组的最小排名 |
max | 使用整个分组的最大排名 |
first | 按值在原始数据中出现的顺序分配排名 |
dense | 与 min 类似,但是排名每次只会增加 1,即并列的数据只占一个名次 |
② 按降序进行排名
其示例代码如下。
In [19]: se = pd.Series([1,3,2,1,2]) In [20]: se.rank(ascending=False, method='max') Out[20]: 0 5.0 1 1.0 2 3.0 3 5.0 4 3.0 dtype: float64
2) DataFrame 的排名
若对 DataFrame 进行排名,则可根据 axis 指定的轴进行排名,axis=0 按行排名,axis=1 按列排名,其示例代码如下。In [21]: df = pd.DataFrame({'x':[4,6,-1],'y':[1,0,2],'z':[5,7,-1]}) In [22]: df.rank(axis=0) Out[22]: X y z 0 2.0 2.0 2.0 1 3.0 1.0 3.0 2 1.0 3.0 1.0