今天在看《Python数据分析实战》的时候发现了一个方法pandas.Series.rank()
当时没有看明白,后来看了文档又结合着例子看懂了(其实超级简单,但是人的脑子有的时候就是有问题吧!一时半会儿转不过来弯儿,2333,可能因为我是傻逼吧) 照例,我们还是先来看看文档: pandas.Series.rank
Series.*rank(axis=0, method='average', numeric_only=None, na_option='keep', ascending=True, pct=False)*
Compute numerical data ranks (1 through n) along axis. Equal values are assigned a rank that is the average of the ranks of those values
我把这个方法称为排位序,就跟考试成绩排第一第二是相同的意思,我们先来看一段代码:
>>> import pandas as pd
>>> ser = pd.Series([5, 0, 3, 8, 4], index=['blue', 'red', 'yellow', 'white', 'green'])
>>> ser
blue 0
red 5
yellow 3
white 8
green 4
dtype: int64
>>> ser.rank()
red 4.0
blue 1.0
yellow 2.0
white 5.0
green 3.0
dtype: float64
>>> ser.rank(ascending=False)
blue 2.0
red 5.0
yellow 4.0
white 1.0
green 3.0
dtype: float64
复制代码
我们这里定义了一个pandas.Series
,这个Series
的index
是'blue', 'red', 'yellow', 'white', 'green'
对应的数值分别为5, 0, 3, 8, 4
,当我们调用pandas.Series.rank
方法时可以看到这个Series
按照index
所对应的数值的大小进行了排位序,从1.0
到5.0
。当我们将参数ascending
设置为False
的时候就按照index
的本身的顺序显示rank
啦!至于别的参数怎么设置,可以设置成什么,你们就去文档里面看吧,嘻嘻! 今天的代码可以在我的Github里找到,如果文章中或者代码中有什么错误还请大家不吝赐教,批评指正!感谢!