Reputation: 1659
Say I have a matrices A, B, and C. When I initialize the matrices to
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
A.shape[0]
gives 1, just like 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.
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!
Upvotes: 0
Views: 224
Reputation: 1659
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.
Upvotes: 0
Reputation: 231385
You could qualify the shape[0]
by the test of whether size
is 0 or not.
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.
Upvotes: 1
Reputation: 280500
A = np.array([[]])
That's a 1-by-0 array. You seem to want a 0-by-3 array. 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
.
Upvotes: 2