python_排名

Sorting and Ranking¶
import pandas as pd
from pandas import Series, DataFrame
import numpy as np
# 排序和排名
# 根据条件对数据集排序(sorting)也是⼀种重要的内置运算。要
# 对⾏或列索引进⾏排序(按字典顺序),可使⽤sort_index⽅
# 法,它将返回⼀个已排序的新对象:
obj = pd.Series(range(4), index=['d', 'a', 'b', 'c'])
obj.sort_index()
a 1
b 2
c 3
d 0
dtype: int64
#
#对于DataFrame,则可以根据任意⼀个轴上的索引进⾏排序
#对索引进行排序
frame = pd.DataFrame(np.arange(8).reshape((2, 4)),
index=['three', 'one'],
columns=['d', 'a', 'b', 'c'])
frame.sort_index()
frame.sort_index(axis=1)
a b c d
three 1 2 3 0
one 5 6 7 4
#数据默认是按升序排序的,但也可以降序排序
frame.sort_index(axis=1, ascending=False)
d c b a
three 0 3 2 1
one 4 7 6 5
obj = pd.Series([4, 7, -3, 2])
obj.sort_values()
2 -3
3 2
0 4
1 7
dtype: int64
#
#若要按值对Series进⾏排序,可使⽤其sort_values⽅法
obj = pd.Series([4, np.nan, 7, np.nan, -3, 2])
obj.sort_values()
4 -3.0
5 2.0
0 4.0
2 7.0
1 NaN
3 NaN
dtype: float64
# 当排序⼀个DataFrame时,你可能希望根据⼀个或多个列中的值
# 进⾏排序
frame = pd.DataFrame({'b': [4, 7, -3, 2], 'a': [0, 1, 0, 1]})
frame
frame.sort_values(by='b')
b a
2 -3 0
3 2 1
0 4 0
1 7 1
# 根据多个列进⾏排序
frame.sort_values(by=['a', 'b'])
b a
2 -3 0
0 4 0
3 2 1
1 7 1
obj = pd.Series([7, -5, 7, 4, 2, 0, 4])
# obj = pd.Series([1,2,3,5,5])
obj.rank()
0 6.5
1 1.0
2 6.5
3 4.5
4 3.0
5 2.0
6 4.5
dtype: float64
# 根据值在原数据中出现的顺序给出排名:
obj.rank(method='first')
0 6.0
1 1.0
2 7.0
3 4.0
4 3.0
5 2.0
6 5.0
dtype: float64
# Assign tie values the maximum rank in the group
obj.rank(ascending=False, method='max')
0 2.0
1 7.0
2 2.0
3 4.0
4 5.0
5 6.0
6 4.0
dtype: float64
frame = pd.DataFrame({'b': [4.3, 7, -3, 2], 'a': [0, 1, 0, 1],
'c': [-2, 5, 8, -2.5]})
frame
frame.rank(axis='columns')
b a c
0 3.0 2.0 1.0
1 3.0 1.0 2.0
2 1.0 2.0 3.0
3 3.0 2.0 1.0