2024年Python最新Numpy详细教程_numpy详细教程 机器学习研究组

  1. >>> b = array( [ (1.5,2,3), (4,5,6) ] )
  2. >>> b
  3. array([[ 1.5,  2. ,  3. ],
  4. [ 4. ,  5. ,  6. ]])

数组类型可以在创建时显示指定

 
  1. >>> c = array( [ [1,2], [3,4] ], dtype=complex )
  2. >>> c
  3. array([[ 1.+0.j,  2.+0.j],
  4. [ 3.+0.j,  4.+0.j]])

通常,数组的元素开始都是未知的,但是它的大小已知。因此,NumPy提供了一些使用占位符创建数组的函数。这最小化了扩展数组的需要和高昂的运算代价。

函数 function创建一个全是0的数组,函数 ones创建一个全1的数组,函数 empty创建一个内容随机并且依赖与内存状态的数组。默认创建的数组类型(dtype)都是float64。

 
  1. >>> zeros( (3,4) )
  2. array([[0.,  0.,  0.,  0.],
  3. [0.,  0.,  0.,  0.],
  4. [0.,  0.,  0.,  0.]])
  5. >>> ones( (2,3,4), dtype=int16 )                # dtype can also be specified
  6. array([[[ 1, 1, 1, 1],
  7. [ 1, 1, 1, 1],
  8. [ 1, 1, 1, 1]],
  9. [[ 1, 1, 1, 1],
  10. [ 1, 1, 1, 1],
  11. [ 1, 1, 1, 1]]], dtype=int16)
  12. >>> empty( (2,3) )
  13. array([[  3.73603959e-262,   6.02658058e-154,   6.55490914e-260],
  14. [  5.30498948e-313,   3.14673309e-307,   1.00000000e+000]])

为了创建一个数列,NumPy提供一个类似arange的函数返回数组而不是列表:

 
  1. >>> arange( 10, 30, 5 )
  2. array([10, 15, 20, 25])
  3. >>> arange( 0, 2, 0.3 )                 # it accepts float arguments
  4. array([ 0. ,  0.3,  0.6,  0.9,  1.2,  1.5,  1.8])

arange使用浮点数参数时,由于有限的浮点数精度,通常无法预测获得的元素个数。因此,最好使用函数 linspace去接收我们想要的元素个数来代替用range来指定步长。

打印数组

当你打印一个数组,NumPy以类似嵌套列表的形式显示它,但是呈以下布局:

最后的轴从左到右打印 次后的轴从顶向下打印 剩下的轴从顶向下打印,每个切片通过一个空行与下一个隔开

一维数组被打印成行,二维数组成矩阵,三维数组成矩阵列表。

 
  1. >>> a = arange(6)                         # 1d array
  2. >>> print a
  3. [0 1 2 3 4 5]
  4. >>>
  5. >>> b = arange(12).reshape(4,3)           # 2d array
  6. >>> print b
  7. [[ 0  1  2]
  8. [ 3  4  5]
  9. [ 6  7  8]
  10. [ 9 10 11]]
  11. >>>
  12. >>> c = arange(24).reshape(2,3,4)         # 3d array
  13. >>> print c
  14. [[[ 0  1  2  3]
  15. [ 4  5  6  7]
  16. [ 8  9 10 11]]
  17. [[12 13 14 15]
  18. [16 17 18 19]
  19. [20 21 22 23]]]

如果一个数组用来打印太大了,NumPy自动省略中间部分而只打印角落

 
  1. >>> print arange(10000)
  2. [   0    1    2 ..., 9997 9998 9999]
  3. >>>
  4. >>> print arange(10000).reshape(100,100)
  5. [[   0    1    2 ...,   97   98   99]
  6. [ 100  101  102 ...,  197  198  199]
  7. [ 200  201  202 ...,  297  298  299]
  8. ...,
  9. [9700 9701 9702 ..., 9797 9798 9799]
  10. [9800 9801 9802 ..., 9897 9898 9899]
  11. [9900 9901 9902 ..., 9997 9998 9999]]

禁用NumPy的这种行为并强制打印整个数组,你可以设置 printoptions参数来更改打印选项。

 
  1. >>> set_printoptions(threshold='nan')

基本运算

数组的算术运算是按元素的。新的数组被创建并且被结果填充。

 
  1. >>> a = array( [20,30,40,50] )
  2. >>> b = arange( 4 )
  3. >>> b
  4. array([0, 1, 2, 3])
  5. >>> c = a-b
  6. >>> c
  7. array([20, 29, 38, 47])
  8. >>> b**2
  9. array([0, 1, 4, 9])
  10. >>> 10*sin(a)
  11. array([ 9.12945251, -9.88031624,  7.4511316 , -2.62374854])
  12. >>> a<35
  13. array([True, True, False, False], dtype=bool)

不像许多矩阵语言,NumPy中的乘法运算符*指示按元素计算,矩阵乘法可以使用dot函数或创建矩阵对象实现

 
  1. >>> A = array( [[1,1],
  2. ...             [0,1]] )
  3. >>> B = array( [[2,0],
  4. ...             [3,4]] )
  5. >>> A*B                         # elementwise product
  6. array([[2, 0],
  7. [0, 4]])
  8. >>> dot(A,B)                    # matrix product
  9. array([[5, 4],
  10. [3, 4]])

有些操作符像 +=*=被用来更改已存在数组而不创建一个新的数组。

 
  1. >>> a = ones((2,3), dtype=int)
  2. >>> b = random.random((2,3))
  3. >>> a *= 3
  4. >>> a
  5. array([[3, 3, 3],
  6. [3, 3, 3]])
  7. >>> b += a
  8. >>> b
  9. array([[ 3.69092703,  3.8324276 ,  3.0114541 ],
  10. [ 3.18679111,  3.3039349 ,  3.37600289]])
  11. >>> a += b                                  # b is converted to integer type
  12. >>> a
  13. array([[6, 6, 6],
  14. [6, 6, 6]])

当运算的是不同类型的数组时,结果数组和更普遍和精确的已知(这种行为叫做upcast)。

 
  1. >>> a = ones(3, dtype=int32)
  2. >>> b = linspace(0,pi,3)
  3. >>> b.dtype.name
  4. 'float64'
  5. >>> c = a+b
  6. >>> c
  7. array([ 1.        ,  2.57079633,  4.14159265])
  8. >>> c.dtype.name
  9. 'float64'
  10. >>> d = exp(c*1j)
  11. >>> d
  12. array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j,
  13. -0.54030231-0.84147098j])
  14. >>> d.dtype.name
  15. 'complex128' 许多非数组运算,如计算数组所有元素之和,被作为ndarray类的方法实现
  16. >>> a = random.random((2,3))
  17. >>> a
  18. array([[ 0.6903007 ,  0.39168346,  0.16524769],
  19. [ 0.48819875,  0.77188505,  0.94792155]])
  20. >>> a.sum()
  21. 3.4552372100521485
  22. >>> a.min()
  23. 0.16524768654743593
  24. >>> a.max()
  25. 0.9479215542670073

这些运算默认应用到数组好像它就是一个数字组成的列表,无关数组的形状。然而,指定 axis参数你可以吧运算应用到数组指定的轴上:

 
  1. >>> b = arange(12).reshape(3,4)
  2. >>> b
  3. array([[ 0,  1,  2,  3],
  4. [ 4,  5,  6,  7],
  5. [ 8,  9, 10, 11]])
  6. >>>
  7. >>> b.sum(axis=0)                            # sum of each column
  8. array([12, 15, 18, 21])
  9. >>>
  10. >>> b.min(axis=1)                            # min of each row
  11. array([0, 4, 8])
  12. >>>
  13. >>> b.cumsum(axis=1)                         # cumulative sum along each row
  14. array([[ 0,  1,  3,  6],
  15. [ 4,  9, 15, 22],
  16. [ 8, 17, 27, 38]])

通用函数(ufunc)

NumPy提供常见的数学函数如 sin, cosexp。在NumPy中,这些叫作“通用函数”(ufunc)。在NumPy里这些函数作用按数组的元素运算,产生一个数组作为输出.

 
  1. >>> B = arange(3)
  2. >>> B
  3. array([0, 1, 2])
  4. >>> exp(B)
  5. array([ 1.        ,  2.71828183,  7.3890561 ])
  6. >>> sqrt(B)
  7. array([ 0.        ,  1.        ,  1.41421356])
  8. >>> C = array([2., -1., 4.])
  9. >>> add(B, C)
  10. array([ 2.,  0.,  6.])

索引,切片和迭代

一维数组可以被索引、切片和迭代,就像列表和其它Python序列。

 
  1. >>> a = arange(10)**3
  2. >>> a
  3. array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])
  4. >>> a[2]
  5. 8
  6. >>> a[2:5]
  7. array([ 8, 27, 64])
  8. >>> a[:6:2] = -1000    # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
  9. >>> a
  10. array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729])
  11. >>> a[ : :-1]                                 # reversed a
  12. array([  729,   512,   343,   216,   125, -1000,    27, -1000,     1, -1000])
  13. >>> for i in a:
  14. ...         print i**(1/3.),
  15. ...
  16. nan 1.0 nan 3.0 nan 5.0 6.0 7.0 8.0 9.0

多维数组可以每个轴有一个索引。这些索引由一个逗号分割的元组给出。

 
  1. >>> def f(x,y):
  2. ...         return 10*x+y
  3. ...
  4. >>> b = fromfunction(f,(5,4),dtype=int)
  5. >>> b
  6. array([[ 0,  1,  2,  3],
  7. [10, 11, 12, 13],
  8. [20, 21, 22, 23],
  9. [30, 31, 32, 33],
  10. [40, 41, 42, 43]])
  11. >>> b[2,3]
  12. 23
  13. >>> b[0:5, 1]                       # each row in the second column of b
  14. array([ 1, 11, 21, 31, 41])
  15. >>> b[ : ,1]                        # equivalent to the previous example
  16. array([ 1, 11, 21, 31, 41])
  17. >>> b[1:3, : ]                      # each column in the second and third row of b
  18. array([[10, 11, 12, 13],
  19. [20, 21, 22, 23]])

当少于轴数的索引被提供时,确失的索引被认为是整个切片:

 
  1. >>> b[-1]                                  # the last row. Equivalent to b[-1,:]
  2. array([40, 41, 42, 43])

b[i]中括号中的表达式被当作i和一系列:,来代表剩下的轴。NumPy也允许你使用“点”像 b[i,...]

点(…)代表许多产生一个完整的索引元组必要的分号。如果x是秩为5的数组(即它有5个轴),那么:

x[1,2,…] 等同于 x[1,2,:,:,:], x[…,3] 等同于 x[:,:,:,:,3] x[4,…,5,:] 等同 x[4,:,:,5,:].

 
  1. >>> c = array( [ [[  0,  1,  2],      # a 3D array (two stacked 2D arrays) ...               [ 10, 12, 13]], ... ...              [[100,101,102], ...               [110,112,113]] ] ) >>> c.shape (2, 2, 3) >>> c[1,...]                          # same as c[1,:,:] or c[1] array([[100, 101, 102],        [110, 112, 113]]) >>> c[...,2]                          # same as c[:,:,2] array([[  2,  13],        [102, 113]])

迭代多维数组是就第一个轴而言的:

 
  1. >>> for row in b:
  2. ...         print row
  3. ...
  4. [0 1 2 3]
  5. [10 11 12 13]
  6. [20 21 22 23]
  7. [30 31 32 33]
  8. [40 41 42 43]

然而,如果一个人想对每个数组中元素进行运算,我们可以使用flat属性,该属性是数组元素的一个迭代器:

 
  1. >>> for element in b.flat:
  2. ...         print element,
  3. ...
  4. 0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43

形状操作

更改数组的形状一个数组的形状由它每个轴上的元素个数给出:

 
  1. >>> a = floor(10*random.random((3,4)))
  2. >>> a
  3. array([[ 7.,  5.,  9.,  3.],
  4. [ 7.,  2.,  7.,  8.],
  5. [ 6.,  8.,  3.,  2.]])
  6. >>> a.shape
  7. (3, 4)

一个数组的形状可以被多种命令修改:

 
  1. >>> a.ravel() # flatten the array
  2. array([ 7.,  5.,  9.,  3.,  7.,  2.,  7.,  8.,  6.,  8.,  3.,  2.])
  3. >>> a.shape = (6, 2)
  4. >>> a.transpose()
  5. array([[ 7.,  9.,  7.,  7.,  6.,  3.],
  6. [ 5.,  3.,  2.,  8.,  8.,  2.]])

ravel()展平的数组元素的顺序通常是“C风格”的,就是说,最右边的索引变化得最快,所以元素a[0,0]之后是a[0,1]。如果数组被改变形状(reshape)成其它形状,数组仍然是“C风格”的。NumPy通常创建一个以这个顺序保存数据的数组,所以 ravel()将总是不需要复制它的参数3。但是如果数组是通过切片其它数组或有不同寻常的选项时,它可能需要被复制。函数 reshape()ravel()还可以被同过一些可选参数构建成FORTRAN风格的数组,即最左边的索引变化最快。 reshape函数改变参数形状并返回它,而resize函数改变数组自身。

 
  1. >>> a
  2. array([[ 7.,  5.],
  3. [ 9.,  3.],
  4. [ 7.,  2.],
  5. [ 7.,  8.],
  6. [ 6.,  8.],
  7. [ 3.,  2.]])
  8. >>> a.resize((2,6))
  9. >>> a
  10. array([[ 7.,  5.,  9.,  3.,  7.,  2.],
  11. [ 7.,  8.,  6.,  8.,  3.,  2.]])

如果在改变形状操作中一个维度被给做-1,其维度将自动被计算

组合(stack)不同的数组

几种方法可以沿不同轴将数组堆叠在一起:

 
  1. >>> a = floor(10*random.random((2,2)))
  2. >>> a
  3. array([[ 1.,  1.],
  4. [ 5.,  8.]])
  5. >>> b = floor(10*random.random((2,2)))
  6. >>> b
  7. array([[ 3.,  3.],
  8. [ 6.,  0.]])
  9. >>> vstack((a,b))
  10. array([[ 1.,  1.],
  11. [ 5.,  8.],
  12. [ 3.,  3.],
  13. [ 6.,  0.]])
  14. >>> hstack((a,b))
  15. array([[ 1.,  1.,  3.,  3.],
  16. [ 5.,  8.,  6.,  0.]])

函数 column_stack以列将一维数组合成二维数组,它等同与 vstack对一维数组。

 
  1. >>> column_stack((a,b))   # With 2D arrays
  2. array([[ 1.,  1.,  3.,  3.],
  3. [ 5.,  8.,  6.,  0.]])
  4. >>> a=array([4.,2.])
  5. >>> b=array([2.,8.])
  6. >>> a[:,newaxis]  # This allows to have a 2D columns vector
  7. array([[ 4.],
  8. [ 2.]])
  9. >>> column_stack((a[:,newaxis],b[:,newaxis]))
  10. array([[ 4.,  2.],
  11. [ 2.,  8.]])
  12. >>> vstack((a[:,newaxis],b[:,newaxis])) # The behavior of vstack is different
  13. array([[ 4.],
  14. [ 2.],
  15. [ 2.],
  16. [ 8.]])

row_stack函数,另一方面,将一维数组以行组合成二维数组。

对那些维度比二维更高的数组, hstack沿着第二个轴组合, vstack沿着第一个轴组合, concatenate允许可选参数给出组合时沿着的轴。 在复杂情况下, r_[]c_[]对创建沿着一个方向组合的数很有用,它们允许范围符号(“:”):

 
  1. >>> r_[1:4,0,4]
  2. array([1, 2, 3, 0, 4])

当使用数组作为参数时,r和c的默认行为和vstack和hstack很像,但是允许可选的参数给出组合所沿着的轴的代号。

将一个数组分割(split)成几个小数组

使用 hsplit你能将数组沿着它的水平轴分割,或者指定返回相同形状数组的个数,或者指定在哪些列后发生分割:

 
  1. >>> a = floor(10*random.random((2,12)))
  2. >>> a
  3. array([[ 8.,  8.,  3.,  9.,  0.,  4.,  3.,  0.,  0.,  6.,  4.,  4.],
  4. [ 0.,  3.,  2.,  9.,  6.,  0.,  4.,  5.,  7.,  5.,  1.,  4.]])
  5. >>> hsplit(a,3)   # Split a into 3
  6. [array([[ 8.,  8.,  3.,  9.],
  7. [ 0.,  3.,  2.,  9.]]), array([[ 0.,  4.,  3.,  0.],
  8. [ 6.,  0.,  4.,  5.]]), array([[ 0.,  6.,  4.,  4.],
  9. [ 7.,  5.,  1.,  4.]])]
  10. >>> hsplit(a,(3,4))   # Split a after the third and the fourth column
  11. [array([[ 8.,  8.,  3.],
  12. [ 0.,  3.,  2.]]), array([[ 9.],
  13. [ 9.]]), array([[ 0.,  4.,  3.,  0.,  0.,  6.,  4.,  4.],
  14. [ 6.,  0.,  4.,  5.,  7.,  5.,  1.,  4.]])]

vsplit沿着纵向的轴分割, array split允许指定沿哪个轴分割。

复制和视图当运算和处理数组时,它们的数据有时被拷贝到新的数组有时不是。这通常是新手的困惑之源。这有三种情况:完全不拷贝简单的赋值不拷贝数组对象或它们的数据。

 
  1. >>> a = arange(12)
  2. >>> b = a            # no new object is created
  3. >>> b is a           # a and b are two names for the same ndarray object
  4. True
  5. >>> b.shape = 3,4    # changes the shape of a
  6. >>> a.shape
  7. (3, 4)

Python 传递不定对象作为参考,所以函数调用不拷贝数组。

 
  1. >>> def f(x):
  2. ...     print id(x)
  3. ...
  4. >>> id(a)                           # id is a unique identifier of an object
  5. 148293216
  6. >>> f(a)
  7. 148293216

视图(view)和浅复制

不同的数组对象分享同一个数据。视图方法创造一个新的数组对象指向同一数据。

 
  1. >>> c = a.view()
  2. >>> c is a
  3. False
  4. >>> c.base is a                        # c is a view of the data owned by a
  5. True
  6. >>> c.flags.owndata
  7. False
  8. >>>
  9. >>> c.shape = 2,6                      # a's shape doesn't change
  10. >>> a.shape
  11. (3, 4)
  12. >>> c[0,4] = 1234                      # a's data changes
  13. >>> a
  14. array([[   0,    1,    2,    3],
  15. [1234,    5,    6,    7],
  16. [   8,    9,   10,   11]])

切片数组返回它的一个视图:

 
  1. >>> s = a[ : , 1:3]     # spaces added for clarity; could also be written "s = a[:,1:3]"
  2. >>> s[:] = 10           # s[:] is a view of s. Note the difference between s=10 and s[:]=10
  3. >>> a
  4. array([[   0,   10,   10,    3],
  5. [1234,   10,   10,    7],
  6. [   8,   10,   10,   11]])

深复制

这个复制方法完全复制数组和它的数据。

 
  1. >>> d = a.copy()                          # a new array object with new data is created
  2. >>> d is a
  3. False
  4. >>> d.base is a                           # d doesn't share anything with a
  5. False
  6. >>> d[0,0] = 9999
  7. >>> a
  8. array([[   0,   10,   10,    3],
  9. [1234,   10,   10,    7],
  10. [   8,   10,   10,   11]])

函数和方法(method)总览

创建数组

 
  1. arange, array, copy, empty, empty_like, eye, fromfile, fromfunction, identity, linspace, logspace, mgrid, ogrid, ones, ones_like, r , zeros, zeros_like

转化

 
  1. astype, atleast 1d, atleast 2d, atleast 3d, mat

操作

 
  1. array split, column stack, concatenate, diagonal, dsplit, dstack, hsplit, hstack, item, newaxis, ravel, repeat, reshape, resize, squeeze, swapaxes, take, transpose, vsplit, vstack

询问

 
  1. all, any, nonzero, where

排序

 
  1. argmax, argmin, argsort, max, min, ptp, searchsorted, sort

运算

 
  1. choose, compress, cumprod, cumsum, inner, fill, imag, prod, put, putmask, real, sum

基本统计

 
  1. cov, mean, std, var

基本线性代数

 
  1. cross, dot, outer, svd, vdot
进阶
广播法则(rule)

广播法则能使通用函数有意义地处理不具有相同形状的输入。

广播第一法则是,如果所有的输入数组维度不都相同,一个“1”将被重复地添加在维度较小的数组上直至所有的数组拥有一样的维度。

广播第二法则确定长度为1的数组沿着特殊的方向表现地好像它有沿着那个方向最大形状的大小。对数组来说,沿着那个维度的数组元素的值理应相同。

应用广播法则之后,所有数组的大小必须匹配。更多细节可以从这个文档找到。

花哨的索引和索引技巧

NumPy比普通Python序列提供更多的索引功能。除了索引整数和切片,正如我们之前看到的,数组可以被整数数组和布尔数组索引。

通过数组索引

 
  1. >>> a = arange(12)**2                          # the first 12 square numbers
  2. >>> i = array( [ 1,1,3,8,5 ] )                 # an array of indices
  3. >>> a[i]                                       # the elements of a at the positions i
  4. array([ 1,  1,  9, 64, 25])
  5. >>>
  6. >>> j = array( [ [ 3, 4], [ 9, 7 ] ] )         # a bidimensional array of indices
  7. >>> a[j]                                       # the same shape as j
  8. array([[ 9, 16],
  9. [81, 49]])

当被索引数组a是多维的时,每一个唯一的索引数列指向a的第一维。以下示例通过将图片标签用调色版转换成色彩图像展示了这种行为。

 
  1. >>> palette = array( [ [0,0,0],                # black
  2. ...                    [255,0,0],              # red
  3. ...                    [0,255,0],              # green
  4. ...                    [0,0,255],              # blue
  5. ...                    [255,255,255] ] )       # white
  6. >>> image = array( [ [ 0, 1, 2, 0 ],           # each value corresponds to a color in the palette
  7. ...                  [ 0, 3, 4, 0 ]  ] )
  8. >>> palette[image]                            # the (2,4,3) color image
  9. array([[[  0,   0,   0],
  10. [255,   0,   0],
  11. [  0, 255,   0],
  12. [  0,   0,   0]],
  13. [[  0,   0,   0],
  14. [  0,   0, 255],
  15. [255, 255, 255],
  16. [  0,   0,   0]]])

我们也可以给出不不止一维的索引,每一维的索引数组必须有相同的形状。

 
  1. >>> a = arange(12).reshape(3,4)
  2. >>> a
  3. array([[ 0,  1,  2,  3],
  4. [ 4,  5,  6,  7],
  5. [ 8,  9, 10, 11]])
  6. >>> i = array( [ [0,1],                        # indices for the first dim of a
  7. ...              [1,2] ] )
  8. >>> j = array( [ [2,1],                        # indices for the second dim
  9. ...              [3,3] ] )
  10. >>>
  11. >>> a[i,j]                                     # i and j must have equal shape
  12. array([[ 2,  5],
  13. [ 7, 11]])
  14. >>>
  15. >>> a[i,2]
  16. array([[ 2,  6],
  17. [ 6, 10]])
  18. >>>
  19. >>> a[:,j]                                     # i.e., a[ : , j]
  20. array([[[ 2,  1],
  21. [ 3,  3]],
  22. [[ 6,  5],
  23. [ 7,  7]],
  24. [[10,  9],
  25. [11, 11]]])

自然,我们可以把i和j放到序列中(比如说列表)然后通过list索引。

 
  1. >>> l = [i,j]
  2. >>> a[l]                                       # equivalent to a[i,j]
  3. array([[ 2,  5],
  4. [ 7, 11]])

然而,我们不能把i和j放在一个数组中,因为这个数组将被解释成索引a的第一维。

 
  1. >>> s = array( [i,j] )
  2. >>> a[s]                                       # not what we want
  3. ---------------------------------------------------------------------------
  4. IndexError                                Traceback (most recent call last)
  5. <ipython-input-100-b912f631cc75> in <module>()
  6. ----> 1 a[s]
  7. IndexError: index (3) out of range (0<=index<2) in dimension 0
  8. >>>
  9. >>> a[tuple(s)]                                # same as a[i,j]
  10. array([[ 2,  5],
  11. [ 7, 11]])

另一个常用的数组索引用法是搜索时间序列最大值。

 
  1. >>> time = linspace(20, 145, 5)                 # time scale
  2. >>> data = sin(arange(20)).reshape(5,4)         # 4 time-dependent series
  3. >>> time
  4. array([  20.  ,   51.25,   82.5 ,  113.75,  145.  ])
  5. >>> data
  6. array([[ 0.        ,  0.84147098,  0.90929743,  0.14112001],
  7. [-0.7568025 , -0.95892427, -0.2794155 ,  0.6569866 ],
  8. [ 0.98935825,  0.41211849, -0.54402111, -0.99999021],
  9. [-0.53657292,  0.42016704,  0.99060736,  0.65028784],
  10. [-0.28790332, -0.96139749, -0.75098725,  0.14987721]])
  11. >>>
  12. >>> ind = data.argmax(axis=0)                   # index of the maxima for each series
  13. >>> ind
  14. array([2, 0, 3, 1])
  15. >>>
  16. >>> time_max = time[ ind]                       # times corresponding to the maxima
  17. >>>
  18. >>> data_max = data[ind, xrange(data.shape[1])] # => data[ind[0],0], data[ind[1],1]...
  19. >>>
  20. >>> time_max
  21. array([  82.5 ,   20.  ,  113.75,   51.25])
  22. >>> data_max
  23. array([ 0.98935825,  0.84147098,  0.99060736,  0.6569866 ])
  24. >>>
  25. >>> all(data_max == data.max(axis=0))
  26. True

你也可以使用数组索引作为目标来赋值:

 
  1. >>> a = arange(5)
  2. >>> a
  3. array([0, 1, 2, 3, 4])
  4. >>> a[[1,3,4]] = 0
  5. >>> a
  6. array([0, 0, 2, 0, 0])

然而,当一个索引列表包含重复时,赋值被多次完成,保留最后的值:

 
  1. >>> a = arange(5)
  2. >>> a[[0,0,2]]=[1,2,3]
  3. >>> a
  4. array([2, 1, 3, 3, 4])

这足够合理,但是小心如果你想用Python的+=结构,可能结果并非你所期望:

 
  1. >>> a = arange(5)
  2. >>> a[[0,0,2]]+=1
  3. >>> a
  4. array([1, 1, 3, 3, 4])

即使0在索引列表中出现两次,索引为0的元素仅仅增加一次。这是因为Python要求a+=1和a=a+1等同。

通过布尔数组索引

一、Python所有方向的学习路线

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

二、学习软件

工欲善其事必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。

三、入门学习视频

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里无偿获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 7
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值