2024年Python最新Numpy详细教程_numpy详细教程 机器学习研究组,字节跳动面试链接

文末有福利领取哦~

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

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

👉二、Python必备开发工具

img
👉三、Python视频合集

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
img

👉 四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。(文末领读者福利)
img

👉五、Python练习题

检查学习结果。
img

👉六、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
img

img

👉因篇幅有限,仅展示部分资料,这份完整版的Python全套学习资料已经上传

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

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

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

  1. 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等同。

通过布尔数组索引

当我们使用整数数组索引数组时,我们提供一个索引列表去选择。通过布尔数组索引的方法是不同的我们显式地选择数组中我们想要和不想要的元素。

我们能想到的使用布尔数组的索引最自然方式就是使用和原数组一样形状的布尔数组。

 
  1. >>> a = arange(12).reshape(3,4)
  2. >>> b = a > 4
  3. >>> b                                          # b is a boolean with a's shape
  4. array([[False, False, False, False],
  5. [False, True, True, True],
  6. [True, True, True, True]], dtype=bool)
  7. >>> a[b]                                       # 1d array with the selected elements
  8. array([ 5,  6,  7,  8,  9, 10, 11])

这个属性在赋值时非常有用:

 
  1. >>> a[b] = 0                                   # All elements of 'a' higher than 4 become 0
  2. >>> a
  3. array([[0, 1, 2, 3],
  4. [4, 0, 0, 0],
  5. [0, 0, 0, 0]])

第二种通过布尔来索引的方法更近似于整数索引;对数组的每个维度我们给一个一维布尔数组来选择我们想要的切片。

 
  1. >>> a = arange(12).reshape(3,4)
  2. >>> b1 = array([False,True,True])             # first dim selection
  3. >>> b2 = array([True,False,True,False])       # second dim selection
  4. >>>
  5. >>> a[b1,:]                                   # selecting rows
  6. array([[ 4,  5,  6,  7],
  7. [ 8,  9, 10, 11]])
  8. >>>
  9. >>> a[b1]                                     # same thing
  10. array([[ 4,  5,  6,  7],
  11. [ 8,  9, 10, 11]])
  12. >>>
  13. >>> a[:,b2]                                   # selecting columns
  14. array([[ 0,  2],
  15. [ 4,  6],
  16. [ 8, 10]])
  17. >>>
  18. >>> a[b1,b2]                                  # a weird thing to do
  19. array([ 4, 10])

注意一维数组的长度必须和你想要切片的维度或轴的长度一致,在之前的例子中,b1是一个秩为1长度为三的数组(a的行数),b2(长度为4)与a的第二秩(列)相一致.

ix_()函数

ix_函数可以为了获得多元组的结果而用来结合不同向量。例如,如果你想要用所有向量a、b和c元素组成的三元组来计算 a+b*c

 
  1. >>> a = array([2,3,4,5])
  2. >>> b = array([8,5,4])
  3. >>> c = array([5,4,6,8,3])
  4. >>> ax,bx,cx = ix_(a,b,c)
  5. >>> ax
  6. array([[[2]],
  7. [[3]],
  8. [[4]],
  9. [[5]]])
  10. >>> bx
  11. array([[[8],
  12. [5],
  13. [4]]])
  14. >>> cx
  15. array([[[5, 4, 6, 8, 3]]])
  16. >>> ax.shape, bx.shape, cx.shape
  17. ((4, 1, 1), (1, 3, 1), (1, 1, 5))
  18. >>> result = ax+bx*cx
  19. >>> result
  20. array([[[42, 34, 50, 66, 26],
  21. [27, 22, 32, 42, 17],
  22. [22, 18, 26, 34, 14]],
  23. [[43, 35, 51, 67, 27],
  24. [28, 23, 33, 43, 18],
  25. [23, 19, 27, 35, 15]],
  26. [[44, 36, 52, 68, 28],
  27. [29, 24, 34, 44, 19],
  28. [24, 20, 28, 36, 16]],
  29. [[45, 37, 53, 69, 29],
  30. [30, 25, 35, 45, 20],
  31. [25, 21, 29, 37, 17]]])
  32. >>> result[3,2,4]
  33. 17
  34. >>> a[3]+b[2]*c[4]
  35. 17

你也可以实行如下简化:

 
  1. def ufunc_reduce(ufct, *vectors):
  2. vs = ix_(*vectors)
  3. r = ufct.identity
  4. for v in vs:
  5. r = ufct(r,v)
  6. return r

然后这样使用它:

 
  1. >>> ufunc_reduce(add,a,b,c)
  2. array([[[15, 14, 16, 18, 13],
  3. [12, 11, 13, 15, 10],
  4. [11, 10, 12, 14,  9]],
  5. [[16, 15, 17, 19, 14],
  6. [13, 12, 14, 16, 11],
  7. [12, 11, 13, 15, 10]],
  8. [[17, 16, 18, 20, 15],
  9. [14, 13, 15, 17, 12],
  10. [13, 12, 14, 16, 11]],
  11. [[18, 17, 19, 21, 16],
  12. [15, 14, 16, 18, 13],
  13. [14, 13, 15, 17, 12]]])

这个reduce与ufunc.reduce(比如说add.reduce)相比的优势在于它利用了广播法则,避免了创建一个输出大小乘以向量个数的参数数组。

线性代数

简单数组运算

 
  1. >>> from numpy import *
  2. >>> from numpy.linalg import *
  3. >>> a = array([[1.0, 2.0], [3.0, 4.0]])
  4. >>> print a
  5. [[ 1.  2.]
  6. [ 3.  4.]]
  7. >>> a.transpose()
  8. array([[ 1.,  3.],
  9. [ 2.,  4.]])
  10. >>> inv(a)
  11. array([[-2. ,  1. ],
  12. [ 1.5, -0.5]])
  13. >>> u = eye(2) # unit 2x2 matrix; "eye" represents "I"
  14. >>> u
  15. array([[ 1.,  0.],
  16. [ 0.,  1.]])
  17. >>> j = array([[0.0, -1.0], [1.0, 0.0]])
  18. >>> dot (j, j) # matrix product
  19. array([[-1.,  0.],
  20. [ 0., -1.]])
  21. >>> trace(u)  # trace
  22. 2.0
  23. >>> y = array([[5.], [7.]])
  24. >>> solve(a, y)
  25. array([[-3.],
  26. [ 4.]])
  27. >>> eig(j)
  28. (array([ 0.+1.j,  0.-1.j]),
  29. array([[ 0.70710678+0.j,  0.70710678+0.j],
  30. [ 0.00000000-0.70710678j,  0.00000000+0.70710678j]]))
  31. Parameters:
  32. square matrix
  33. Returns
  34. The eigenvalues, each repeated according to its multiplicity.
  35. The normalized (unit "length") eigenvectors, such that the
  36. column ``v[:,i]`` is the eigenvector corresponding to the
  37. eigenvalue ``w[i]`` .

矩阵类

这是一个关于矩阵类的简短介绍。

 
  1. >>> A = matrix('1.0 2.0; 3.0 4.0')
  2. >>> A
  3. [[ 1.  2.]
  4. [ 3.  4.]]
  5. >>> type(A)  # file where class is defined
  6. <class 'numpy.matrixlib.defmatrix.matrix'>
  7. >>> A.T  # transpose
  8. [[ 1.  3.]
  9. [ 2.  4.]]
  10. >>> X = matrix('5.0 7.0')
  11. >>> Y = X.T
  12. >>> Y
  13. [[5.]
  14. [7.]]
  15. >>> print A*Y  # matrix multiplication
  16. [[19.]
  17. [43.]]
  18. >>> print A.I  # inverse
  19. [[-2.   1. ]
  20. [ 1.5 -0.5]]
  21. >>> solve(A, Y)  # solving linear equation
  22. matrix([[-3.],
  23. [ 4.]])

索引:比较矩阵和二维数组

注意NumPy中数组和矩阵有些重要的区别。NumPy提供了两个基本的对象:一个N维数组对象和一个通用函数对象。其它对象都是建构在它们之上 的。特别的,矩阵是继承自NumPy数组对象的二维数组对象。对数组和矩阵,索引都必须包含合适的一个或多个这些组合:整数标量、省略号 (ellipses)、整数列表;布尔值,整数或布尔值构成的元组,和一个一维整数或布尔值数组。矩阵可以被用作矩阵的索引,但是通常需要数组、列表或者 其它形式来完成这个任务。

像平常在Python中一样,索引是从0开始的。传统上我们用矩形的行和列表示一个二维数组或矩阵,其中沿着0轴的方向被穿过的称作行,沿着1轴的方向被穿过的是列。

让我们创建数组和矩阵用来切片

 
  1. >>> A = arange(12)
  2. >>> A
  3. array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
  4. >>> A.shape = (3,4)
  5. >>> M = mat(A.copy())
  6. >>> print type(A),"  ",type(M)
  7. <type 'numpy.ndarray'>    <class 'numpy.core.defmatrix.matrix'>
  8. >>> print A
  9. [[ 0  1  2  3]
  10. [ 4  5  6  7]
  11. [ 8  9 10 11]]
  12. >>> print M
  13. [[ 0  1  2  3]
  14. [ 4  5  6  7]
  15. [ 8  9 10 11]]

现在,让我们简单的切几片。基本的切片使用切片对象或整数。例如, A[:]M[:]的求值将表现得和Python索引很相似。然而要注意很重要的一点就是NumPy切片数组不创建数据的副本;切片提供统一数据的视图。

 
  1. >>> print A[:]; print A[:].shape
  2. [[ 0  1  2  3]
  3. [ 4  5  6  7]
  4. [ 8  9 10 11]]
  5. (3, 4)
  6. >>> print M[:]; print M[:].shape
  7. [[ 0  1  2  3]
  8. [ 4  5  6  7]
  9. [ 8  9 10 11]]
  10. (3, 4)

现在有些和Python索引不同的了:你可以同时使用逗号分割索引来沿着多个轴索引。

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值