Python Numpy 中的矩阵索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34026505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:21:52  来源:igfitidea点击:

Matrix indexing in Numpy

pythonnumpymatrix

提问by cangrejo

I was growing confused during the development of a small Python script involving matrix operations, so I fired up a shell to play around with a toy example and develop a better understanding of matrix indexing in Numpy.

在开发一个涉及矩阵运算的小型 Python 脚本的过程中,我越来越困惑,所以我启动了一个 shell 来玩一个玩具示例,并更好地理解 Numpy 中的矩阵索引。

This is what I did:

这就是我所做的:

>>> import numpy as np
>>> A = np.matrix([1,2,3])
>>> A
matrix([[1, 2, 3]])
>>> A[0]
matrix([[1, 2, 3]])
>>> A[0][0]
matrix([[1, 2, 3]])
>>> A[0][0][0]
matrix([[1, 2, 3]])
>>> A[0][0][0][0]
matrix([[1, 2, 3]])

As you can imagine, this has nothelped me develop a better understanding of matrix indexing in Numpy. This behavior would make sense for something that I would describe as "An array of itself", but I doubt anyone in their right mind would choose that as a model for matrices in a scientific library.

可以想象,这并没有帮助我更好地理解 Numpy 中的矩阵索引。这种行为对于我将其描述为“自身数组”的东西来说是有意义的,但我怀疑任何头脑正常的人都会选择它作为科学图书馆中矩阵的模型。

What is, then, the logic to the output I obtained? Why would the first element of a matrix object be itself?

那么,我获得的输出的逻辑是什么?为什么矩阵对象的第一个元素是它自己?

PS: I know how to obtain the first entry of the matrix. What I am interested in is the logic behind this design decision.

PS:我知道如何获得矩阵的第一个条目。我感兴趣的是这个设计决策背后的逻辑。

EDIT: I'm not asking how to access a matrix element, or why a matrix row behaves like a matrix. I'm asking for a definition of the behavior of a matrix when indexed with a single number. It's an action typical of arrays, but the resulting behavior is nothing like the one you would expect from an array. I would like to know how this is implemented and what's the logic behind the design decision.

编辑:我不是在问如何访问矩阵元素,或者为什么矩阵行的行为像矩阵。当用单个数字索引时,我要求定义矩阵的行为。这是数组的典型操作,但结果行为与您对数组的期望完全不同。我想知道这是如何实现的以及设计决策背后的逻辑是什么。

采纳答案by hpaulj

Look at the shape after indexing:

看索引后的形状:

In [295]: A=np.matrix([1,2,3])
In [296]: A.shape
Out[296]: (1, 3)
In [297]: A[0]
Out[297]: matrix([[1, 2, 3]])
In [298]: A[0].shape
Out[298]: (1, 3)

The key to this behavior is that np.matrixis always 2d. So even if you select one row (A[0,:]), the result is still 2d, shape (1,3). So you can string along as many [0]as you like, and nothing new happens.

这种行为的关键是它np.matrix始终是 2d。因此,即使您选择一行 ( A[0,:]),结果仍然是 2d, shape (1,3)。因此,您可以随心所欲地串[0]起来,而不会发生任何新的事情。

What are you trying to accomplish with A[0][0]? The same as A[0,0]? For the base np.ndarrayclass these are equivalent.

你想用A[0][0]什么来完成?一样A[0,0]吗?对于基np.ndarray类,这些是等效的。

Note that Pythoninterpreter translates indexing to __getitem__calls.

请注意,Python解释器将索引转换为__getitem__调用。

 A.__getitem__(0).__getitem__(0)
 A.__getitem__((0,0))

[0][0]is 2 indexing operations, not one. So the effect of the second [0]depends on what the first produces.

[0][0]是 2 个索引操作,而不是一个。所以第二个的效果[0]取决于第一个产生什么。

For an array A[0,0]is equivalent to A[0,:][0]. But for a matrix, you need to do:

对于数组A[0,0]等价于A[0,:][0]. 但是对于矩阵,您需要执行以下操作:

In [299]: A[0,:][:,0]
Out[299]: matrix([[1]])  # still 2d

=============================

==============================

"An array of itself", but I doubt anyone in their right mind would choose that as a model for matrices in a scientific library.

What is, then, the logic to the output I obtained? Why would the first element of a matrix object be itself?

In addition, A[0,:] is not the same as A[0]

“自身的数组”,但我怀疑任何头脑正常的人都会选择它作为科学图书馆中矩阵的模型。

那么,我获得的输出的逻辑是什么?为什么矩阵对象的第一个元素是它自己?

另外,A[0,:] 和 A[0] 不一样

In light of these comments let me suggest some clarifications.

鉴于这些评论,让我提出一些澄清建议。

A[0]does not mean 'return the 1st element'. It means select along the 1st axis. For a 1d array that means the 1st item. For a 2d array it means the 1st row. For ndarraythat would be a 1d array, but for a matrixit is another matrix. So for a 2d array or matrix, A[i,:]is the same thing as A[i].

A[0]并不意味着“返回第一个元素”。这意味着沿第一轴选择。对于表示第一项的一维数组。对于二维数组,它意味着第一行。因为ndarray那将是一个一维数组,但对于一个matrix它是另一个matrix. 所以对于二维数组或矩阵,A[i,:]A[i].

A[0]does not just return itself. It returns a new matrix. Different id:

A[0]不只是返回自身。它返回一个新矩阵。不同id

In [303]: id(A)
Out[303]: 2994367932
In [304]: id(A[0])
Out[304]: 2994532108

It may have the same data, shape and strides, but it's a new object. It's just as unique as the ithrow of a many row matrix.

它可能具有相同的数据、形状和步幅,但它是一个新对象。它ith与多行矩阵的行一样独特。

Most of the unique matrixactivity is defined in: numpy/matrixlib/defmatrix.py. I was going to suggest looking at the matrix.__getitem__method, but most of the action is performed in np.ndarray.__getitem__.

大多数独特的matrix活动定义在:numpy/matrixlib/defmatrix.py。我打算建议查看该matrix.__getitem__方法,但大部分操作都是在np.ndarray.__getitem__.

np.matrixclass was added to numpyas a convenience for old-school MATLAB programmers. numpyarrays can have almost any number of dimensions, 0, 1, .... MATLAB allowed only 2, though a release around 2000 generalized it to 2 or more.

np.matrix添加类是为了numpy方便老派 MATLAB 程序员。 numpy数组几乎可以有任意数量的维度,0、1、...。MATLAB 只允许 2 个,尽管 2000 年左右的版本将其概括为 2 个或更多。

回答by Mona Jalal

Imagine you have the following

想象一下你有以下

>> A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) 

If you want to get the second column value, use the following:

如果要获取第二列值,请使用以下命令:

>> A.T[1]
array([ 2,  6, 10])