博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Pyhton、Numpy、Pandas排序小结
阅读量:4069 次
发布时间:2019-05-25

本文共 3179 字,大约阅读时间需要 10 分钟。

Python Help

#用built-in函数sorted进行排序,返回副本,原始输入不变sorted(...)    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list#用List的成员函数sort进行排序,在本地进行排序,不返回副本sort(...)    L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;    cmp(x, y) -> -1, 0, 1

参数说明

  • cmp:接受函数(传入函数,函数亦对象)
  • key:接受函数,这个函数只接受一个值。

operator函数

# Help on class itemgetter in module operator:class itemgetter(__builtin__.object) |  itemgetter(item, ...) --> itemgetter object | |  Return a callable object that fetches the given item(s) from its operand. |  After f = itemgetter(2), the call f(r) returns r[2]. |  After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])In [2]: from operator import itemgetterIn [3]: a = [1, 2, 3]In [4]: b = itemgetter(1)In [5]: b(a)Out[5]: 2In [7]: students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]# Use key functionIn [8]: sorted(students, key=lambda student : student[2])Out[8]: [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]# Use cmp functionIn [9]: sorted(students, cmp=lambda x,y : cmp(x[2], y[2]))Out[9]: [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]# Use operator.itemgetterIn [10]: sorted(students, key=itemgetter(2))Out[10]: [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]# 用operator函数实现多级排序In [11]: sorted(students, key=itemgetter(1,2))Out[11]: [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]# 对字典排序,返回由tuple组成的List,不再是字典In [12]: d = {'data1':3, 'data2':1, 'data3':2, 'data4':4}In [13]: sorted(d.iteritems(), key=itemgetter(1), reverse=True)Out[13]: [('data4', 4), ('data1', 3), ('data3', 2), ('data2', 1)]

Numpy

跟Python内置的列表一样,ndarray的sort实例方法也是就地排序。

但是,numpy.sort会为原数组创建一个已排序副本。 (类似于List.sort() -> 就地排序 | sorted() -> 返回副本)

两个排序方法(np.sort(arr) and arr.sort())都可以接受一个axis参数,以便沿指定轴向对各块数据进行单独排序。

间接排序

arr.argsort() and numpy.lexsort(): 索引值说明了数据在新顺序下的位置。

注: Series和DataFrame的sort_index以及Series的order方法就是通过这些函数的变体实现的。

Pandas

sort_index()

对行或列索引进行排序

In [1]: import pandas as pdIn [2]: from pandas import DataFrame, SeriesIn [3]: obj = Series(range(4), index=['d','a','b','c'])In [4]: objOut[4]:d    0a    1b    2c    3dtype: int64In [5]: obj.sort_index()Out[5]:a    1b    2c    3d    0dtype: int64In [6]: import numpy as npIn [8]: frame = DataFrame(np.arange(8).reshape((2,4)), index=['three','one'],   ...:                   columns=['d','a','b','c'])In [9]: frameOut[9]:       d  a  b  cthree  0  1  2  3one    4  5  6  7In [10]: frame.sort_index()Out[10]:       d  a  b  cone    4  5  6  7three  0  1  2  3In [11]: frame.sort_index(axis=1)Out[11]:       a  b  c  dthree  1  2  3  0one    5  6  7  4In [12]: frame.sort_index(axis=1, ascending=False)Out[12]:       d  c  b  athree  0  3  2  1one    4  7  6  5

sort_values

对Series按进行排序, 排序时,任何缺失值默认都会被放到Series的末尾。

In [18]: obj = Series([4, np.nan, 6, np.nan, -3, 2])In [19]: objOut[19]:0    4.01    NaN2    6.03    NaN4   -3.05    2.0dtype: float64In [21]: obj.sort_values()Out[21]:4   -3.05    2.00    4.02    6.01    NaN3    NaNdtype: float64

在DataFrame上,根据一个或多个列中的值进行排序。将一个或多个列的名字传递给by选项即可达到该目的:

In [16]: frame.sort_values(by='b')Out[16]:       d  a  b  cthree  0  1  2  3one    4  5  6  7

间接统计

idxmin, idxmax:达到最小值或最大值的索引。

转载地址:http://qjoji.baihongyu.com/

你可能感兴趣的文章
less 快速入门(一)
查看>>
less语言特性(二)
查看>>
less函数手册(三)
查看>>
less入门教程一
查看>>
less入门教程二
查看>>
less入门教程三(函数手册)
查看>>
监控服务器端口,Down掉会自动重启,并发送邮件 Linux Shell
查看>>
git clone 地址 时,出现错误解决方案
查看>>
二维码生成及解析类
查看>>
生成二维码 及 添加外边框和中间logo
查看>>
Git提交错误:RPC failed; result=22, HTTP code = 411
查看>>
Druid使用ConfigFilter
查看>>
Elicpse使用技巧-打开选中文件文件夹或者包的当前目录
查看>>
eclips 运行项目内存不足的解决方案
查看>>
linux 挂载盘阵 smb
查看>>
JAVA 内存溢出 分析
查看>>
【Java高级开发工程师】近一个月的面试总结
查看>>
分布式事务的典型处理方式:2PC、TCC、异步确保和最大努力型
查看>>
Spring中配置事物注解的方式: @Transactional
查看>>
java中的SPI机制
查看>>