如何在 python 中找到 numpy 矩阵的长度(或维度、大小)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14847457/
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
How do I find the length (or dimensions, size) of a numpy matrix in python?
提问by Kyle Heuton
For a numpy matrix in python
对于python中的numpy矩阵
from numpy import matrix
A = matrix([[1,2],[3,4]])
How can I find the length of a row (or column) of this matrix? Equivalently, how can I know the number of rows or columns?
我怎样才能找到这个矩阵的行(或列)的长度?同样,我如何知道行数或列数?
So far, the only solution I've found is:
到目前为止,我找到的唯一解决方案是:
len(A)
len(A[:,1])
len(A[1,:])
Which returns 2, 2, and 1, respectively. From this I've gathered that len()will return the number of rows, so I can always us the transpose, len(A.T), for the number of columns. However, this feels unsatisfying and arbitrary, as when reading the line len(A), it isn't immediately obvious that this should return the number of rows. It actually works differently than len([1,2])would for a 2D python array, as this would return 2.
分别返回 2、2 和 1。从这里我收集了len()将返回行数的信息,因此我始终可以将转置len(A.T), 用于列数。然而,这让人感到不满意和武断,因为在阅读 line 时len(A),它应该返回行数并不是很明显。它实际上与len([1,2])2D python 数组的工作方式不同,因为这将返回 2。
So, is there a more intuitive way to find the size of a matrix, or is this the best I have?
那么,有没有更直观的方法来找到矩阵的大小,或者这是我拥有的最好的方法?
采纳答案by Kyle Heuton
shapeis a property of both numpy ndarray's and matrices.
shape是 numpy ndarray 和矩阵的属性。
A.shape
will return a tuple (m, n), where m is the number of rows, and n is the number of columns.
将返回一个元组 (m, n),其中 m 是行数,n 是列数。
In fact, the numpy matrixobject is built on top of the ndarrayobject, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray
实际上,numpymatrix对象是建立在对象之上的ndarray,是 numpy 的两个基本对象之一(以及一个通用函数对象),因此它继承自ndarray
回答by hd1
matrix.sizeaccording to the numpy docsreturns the Number of elements in the array.Hope that helps.
matrix.size根据numpy docs返回Number of elements in the array.有帮助的希望。

