【Python笔记】pandas排序和排名


排序

对行或列索引进行排序(按字典序),可使用sort_index方法,将返回一个已排序的新对象。

Series

obj=pd.Series(range(4),index=list('dabc'))
# d    0
# a    1
# b    2
# c    3
# dtype: int64

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=list('dabc'))
dabc
three0123
one4567
frame.sort_index()
dabc
one4567
three0123
frame.sort_index(axis=1)
abcd
three1230
one5674
frame.sort_index(axis=1,ascending=False)
dcba
three0321
one4765

排名

在这里插入图片描述

Series

obj=pd.Series([7,-5,7,4,2,0,4])

# 默认给出平均排名
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

# 使用整个分组的最大排名,降序
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

DataFrame

frame=pd.DataFrame({'b':[4.3,7,-3,2],'a':[0,1,0,1],'c':[-2,5,8,-2.5]})
bac
04.30-2.0
17.015.0
2-3.008.0
32.01-2.5
frame.rank(axis=1) # 横轴排序
bac
03.02.01.0
13.01.02.0
21.02.03.0
33.02.01.0
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值