本文共 3179 字,大约阅读时间需要 10 分钟。
#用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
参数说明
# 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)]
跟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方法就是通过这些函数的变体实现的。
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/