0

I want to write a function that takes a numpy array and I want to check if it meets the requirements. One thing that confuses me is that:

np.array([1,2,3]).shape = np.array([[1,2,3],[2,3],[2,43,32]]) = (3,)

[1,2,3] should be allowed, while [[1,2,3],[2,3],[2,43,32]] shouldn't.

Allowed shapes:

[0, 1, 2, 3, 4]
[0, 1, 2]
[[1],[2]]
[[1, 2], [2, 3], [3, 4]]

Not Allowed:

[] (empty array is not allowed)
[[0], [1, 2]] (inner dimensions must have same size 1!=2)
[[[4,5,6],[4,3,2][[2,3,2],[2,3,4]]] (more than 2 dimension)
2
  • The problem here is in dimensions of np.array([[1,2,3],[2,3],[2,43,32]]). [2, 3] causes dimensions conflict. If you take np.array([[1,2,3],[2,3, None],[2,43,32]]) its shape will be just fine: (3, 3). Commented Feb 10, 2019 at 16:03
  • 1
    Look at the dtype as well as the shape Commented Feb 10, 2019 at 17:09

1 Answer 1

2

You should start with defining what you want in terms of shape. I tried to understand it from the question, please add more details if it is not correct.

So here we have (1) empty array is not allowed and (2) no more than two dimensions. It translates the following way:

def is_allowed(arr):
  return arr.shape != (0, ) and len(arr.shape) <= 2

The first condition just compares you array's shape with the shape of an empty array. the second condition checks that an array has no more than two dimensions.

With inner dimensions there is a problem. Some of the lists you provided as an example are not numpy arrays. If you cast np.array([[1,2,3],[2,3],[2,43,32]]), you get just an array where each element is the list. It is not a "real" numpy array with direct access to all the elements. See example:

>>> np.array([[1,2,3],[2,3],[2,43,32]])
array([list([1, 2, 3]), list([2, 3]), list([2, 43, 32])], dtype=object)
>>> np.array([[1,2,3],[2,3, None],[2,43,32]])
array([[1, 2, 3],
       [2, 3, None],
       [2, 43, 32]], dtype=object)

So I would recommend (if you are operating with usual lists) check that all arrays have the same length without numpy.

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

2 Comments

How can I check when I have a given numpy array if it is "real"? Edit: @hpaulj suggested to check dtype and this should do the job.
Check its dtype.

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.