这里有numpy数组的相关介绍//www.jb51.net/article/130657.htm
排序
numpy与python列表内置的方法类似,也可通过sort方法进行排序。
用法如下:
In [1]: import numpy as npIn [2]: x = np.random.randn(9)In [3]: xOut[3]:array([-0.4041504 , -0.42198556, 0.92807217, -2.66609196, 1.50915897, 0.38080873, 1.05325796, -1.16488798, 0.04062064])In [4]: x.sort()In [5]: xOut[5]:array([-2.66609196, -1.16488798, -0.42198556, -0.4041504 , 0.04062064, 0.38080873, 0.92807217, 1.05325796, 1.50915897])
可以发现上述的sort方法是直接对x进行了排序而并没有创建一个副本。
但是np.sort()这个顶级的方法,会返回一个副本:
In [6]: x = np.random.randn(6)In [7]: xOut[7]:array([ 0.14240205, 0.48903869, 0.22528632, 1.31659382, 0.00352338, 0.95574862])In [8]: np.sort(x)Out[8]:array([ 0.00352338, 0.14240205, 0.22528632, 0.48903869, 0.95574862, 1.31659382])In [9]: xOut[9]:array([ 0.14240205, 0.48903869, 0.22528632, 1.31659382, 0.00352338, 0.95574862])
传入轴编号,可以实现在某一个轴向上进行排序。
In [34]: x = np.random.randn(5,4)In [35]: xOut[35]:array([[-0.26646799, -0.40714749, -0.76788268, -0.25340467], [ 0.70099086, -0.88716684, 0.13461279, 2.14412835], [ 0.39718924, -0.14671297, -0.67821163, 1.85798273], [-0.29389289, 0.0346094 , 0.25213133, 0.87105479], [-0.10797243, 1.60188878, 0.67829493, 0.43291808]])In [36]: s = xIn [37]: s.sort(0)#按列进行排序In [38]: sOut[38]:array([[-0.29389289, -0.88716684, -0.76788268, -0.25340467], [-0.26646799, -0.40714749, -0.67821163, 0.43291808], [-0.10797243, -0.14671297, 0.13461279, 0.87105479], [ 0.39718924, 0.0346094 , 0.25213133, 1.85798273], [ 0.70099086, 1.60188878, 0.67829493, 2.14412835]])In [39]: xOut[39]:array([[-0.29389289, -0.88716684, -0.76788268, -0.25340467], [-0.26646799, -0.40714749, -0.67821163, 0.43291808], [-0.10797243, -0.14671297, 0.13461279, 0.87105479], [ 0.39718924, 0.0346094 , 0.25213133, 1.85798273], [ 0.70099086, 1.60188878, 0.67829493, 2.14412835]])In [40]: x = np.random.randn(5,4)In [41]: xOut[41]:array([[ 0.82309157, -0.56413805, -0.1766557 , -0.31924962], [-1.25606694, 2.63622922, 2.47481377, 0.27840961], [ 0.63659583, 1.52779004, -0.90582752, 0.82325241], [-1.52664294, -0.5285837 , -1.96380368, -0.44323125], [ 1.94859294, 2.55676806, 1.53614848, -0.43366557]])In [42]: x.sort(1)#按行进行排序In [43]: xOut[43]:array([[-0.56413805, -0.31924962, -0.1766557 , 0.82309157], [-1.25606694, 0.27840961, 2.47481377, 2.63622922], [-0.90582752, 0.63659583, 0.82325241, 1.52779004], [-1.96380368, -1.52664294, -0.5285837 , -0.44323125], [-0.43366557, 1.53614848, 1.94859294, 2.55676806]])
在这儿,我试图将x赋值给s,结果发现对s排序后,x也变了,这说明,在内存中,实际上,s,x是指向同一组值得。
新闻热点
疑难解答