python sort、sort_index方法代码实例

yipeiwu_com6年前Python基础

本文实例为大家分享了python sort、sort_index的具体代码,供大家参考,具体内容如下

对Series进行排序

#生成序列obj
obj=pd.Series([4,9,6,20,4],index=['d','a','e','b','c'])
d   4
a   9
e   6
b  20
c   4
dtype: int64

#按obj的索引排序,默认升序,降序可在括号加ascending=False
obj.sort_index()
a   9
b  20
c   4
d   4
e   6
dtype: int64

#按obj的值排序,默认升序
obj.order()
d   4
c   4
e   6
a   9
b  20
dtype: int64

对DataFrame进行排序

#生成frame
frame=pd.DataFrame(pd.Series([3,5,2,6,9,23,12,34,12,15,11,0]).reshape(3,4),columns=['c','f','d','a'],index=['C','A','B'])
  c  f  d  a
C  3  5  2  6
A  9  23 12 34
B  12 15 11 0

#按frame的行索引进行排序
frame.sort_index()
  c  f  d  a
A  9  23 12 34
B  12 15 11 0
C  3  5  2  6

#按frame的列索引进行排序
frame.sort_index(axis=1)
  a  c  d  f
C  6  3  2  5
A  34 9  12 23
B  0  12 11 15

#按frame的一个列或多个列的值进行排序
frame.sort_index(by='a')
  c  f  d  a
B  12 15 11 0
C  3  5  2  6
A  9  23 12 34
frame.sort_index(by=['a','c'])
  c  f  d  a
B  12 15 11 0
C  3  5  2  6
A  9  23 12 34

以上所述是小编给大家介绍的python sort、sort_index方法详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

对django views中 request, response的常用操作详解

request 获取post请求中的json数据 def hello(request): data = json.loads(request.body) ... json格式还...

python的urllib模块显示下载进度示例

复制代码 代码如下: def report_hook(count, block_size, total_size):...     pr...

Python实现保证只能运行一个脚本实例

保证只能运行一个脚本实例,方法是程序运行时监听一个特定端口,如果失败则说明已经有实例在跑。 使用装饰器实现,便于重用 复制代码 代码如下: import functools def ju...

python统计日志ip访问数的方法

本文实例讲述了python统计日志ip访问数的方法。分享给大家供大家参考。具体如下: import re f=open("/tmp/a.log","r") arr={} lines...

Python读取Word(.docx)正文信息的方法

Python读取Word(.docx)正文信息的方法

本文介绍用Python简单读取*.docx文件信息,一些python-word库就是对这种方法的扩展。 介绍分两部分: Word(*.docx)文件简述 Python提取Wor...