0

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!

3 Answers 3

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That doesn't solve my problem, since I'm pulling in the array from a csv, which may potentially be blank. Your answer might be helpful to someone else though.
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.