简体   繁体   English

空矩阵的Python Numpy 2D数组行数仍为1

[英]Python Numpy 2D Array Number of Rows For Empty Matrix is Still 1

Say I have a matrices A, B, and C. When I initialize the matrices to 假设我有一个矩阵A,B和C。当我将矩阵初始化为

A = np.array([[]])
B = np.array([[1,2,3]])
C = np.array([[1,2,3],[4,5,6]])

Then 然后

B.shape[0]
C.shape[0]

give 1 and 2, respectively (as expected), but 分别给出1和2(如预期),但是

A.shape[0]

gives 1, just like B.shape[0]. 给出1,就像B.shape [0]一样。

What is the simplest way to get the number of rows of a given matrix, but still ensure that an empty matrix like A gives a value of zero. 获取给定矩阵的行数的最简单方法是什么,但仍然要确保像A这样的空矩阵的值为零。

After searching stack overflow for awhile, I couldn't find an answer, so I'm posting my own below, but if you can come up with a cleaner, more general answer, I'll accept your answer instead. 在搜索堆栈溢出一段时间后,我找不到答案,因此我在下面发布了自己的答案,但是如果您能提出一个更简洁,更一般的答案,我会接受您的答案。 Thanks! 谢谢!

A = np.array([[]])

That's a 1-by-0 array. 那是一个1×0的数组。 You seem to want a 0-by-3 array. 您似乎想要一个0×3的数组。 Such an array is almost completely useless, but if you really want one, you can make one: 这样的数组几乎完全没有用,但是如果您真的想要一个数组,则可以创建一个数组:

A = np.zeros([0, 3])

Then you'll have A.shape[0] == 0 . 然后,您将获得A.shape[0] == 0

You could qualify the shape[0] by the test of whether size is 0 or not. 您可以通过测试size是否为0来限定shape[0]

In [121]: A.shape[0]*(A.size>0)
Out[121]: 0
In [122]: B.shape[0]*(B.size>0)
Out[122]: 1
In [123]: C.shape[0]*(C.size>0)
Out[123]: 2

or test the number of columns 或测试列数

In [125]: A.shape[0]*(A.shape[1]>0)
Out[125]: 0

What's distinctive about A is the number of columns, the 2nd dimension. A的独特之处在于第二维的列数。

Using 使用

A.size/(len(A[0]) or 1)
B.size/(len(B[0]) or 1)
C.size/(len(C[0]) or 1)

yields 0, 1, and 2, respectively. 分别产生0、1和2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM