array[i][:] 和 array[i,:] 的区别

Lau*_*uro 6 python arrays indexing numpy

我是 python 的新手,所以我习惯使用array[i][j]而不是array[i,j]. 今天,我按照教程创建的脚本不起作用,直到我发现我正在使用

numpy.dot(P[0][:], Q[:][0])
Run Code Online (Sandbox Code Playgroud)

代替

numpy.dot(P[0,:], Q[:,0])
Run Code Online (Sandbox Code Playgroud)

出于某种原因,第二个有效,而第一个给了我一个形状错误。矩阵维度是 MxK 和 KxN。

我试图同时打印P[0][:]P[0,:]运行id()type()并且P[0][:].shape,也没有找到一个理由吧。为什么这些东西不一样?

我在 Jupyter Notebook 4.3.0 和 Python 2.7.13 上运行它。

MSe*_*ert 6

在处理 numpy 数组时,您几乎应该总是使用[i, j]而不是[i][j]。在许多情况下没有真正的区别,但在你的情况下有。

假设你有一个这样的数组:

>>> import numpy as np
>>> arr = np.arange(16).reshape(4, 4)
>>> arr 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
Run Code Online (Sandbox Code Playgroud)

当您使用[:]它时,相当于一个新视图,但如果您这样做[1, :][:, 1]则意味着获得第二行(列)。粗略地说,这意味着:索引您拥有数字的维度,并留下您拥有数字的维度:

>>> arr[:]
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

>>> arr[:, 1]  #  get the second column
array([ 1,  5,  9, 13])
>>> arr[:][1]  # get a new view of the array, then get the second row
array([4, 5, 6, 7])
Run Code Online (Sandbox Code Playgroud)

这是因为[1]被解释为[1, ...](...是省略号对象) 并且对于 2D 它相当于[1, :].

这也是行索引仍然有效的原因(因为它是第一个维度):

>>> arr[1, :]  # get the second row
array([4, 5, 6, 7])
>>> arr[1][:]  # get the second row, then get a new view of that row
array([4, 5, 6, 7])
Run Code Online (Sandbox Code Playgroud)