2

How do I check if a numpy array has a regular shape.

In the example below x is a *2 by 3* matrix. However y is not regular in the sense that it can't be represented as a proper matrix.

Given that I have a numpy array, is there a method (preferably in-built) that I can use to check that the numpy array is an actual matrix

In [9]: import numpy as np                                                      

In [10]: x = np.array([[1,2,3],[4,5,6]])                                        

In [11]: x.shape                                                                
Out[11]: (2, 3)

In [12]: y = np.array([[1,2,3],[4,5]])                                          

In [13]: y.shape                                                                
Out[13]: (2,)
0

3 Answers 3

2

Both are arrays and those are valid shapes. But, with normal, think you meant that each element has the same shape and length across it. For that, a better way would be to check for the datatype. For the variable length case, it would be object. So, we can check for that condition and call out accordingly. Hence, simply do -

def is_normal_arr(a): # a is input array to be tested
    return a.dtype is not np.dtype('object')
Sign up to request clarification or add additional context in comments.

Comments

1

I think the .shape method is capable of checking it. If you input an array which can form a matrix it returns it's actual shape, (2, 3) in your case. If you input an incorrect matrix it returns something like (2,), which says something's wrong with the second dimension, so it can't form a matrix.

2 Comments

replace "correct/incorrect array" with "correct/incorrect matrix". All of them are correct arrays ;)
Yes, true. Thank you
0

Here y is a one-dimensional array and the size of y is 2. y contains 2 list values. AND x is our actual matrix in a proper format.

check the dimensions by y.ndim AND x.ndim.

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.