1

The tuple holding the dimensions of a numpy array (numpy.ndarray.shape) changes size. E.g:

len(numpy.array([1,2,3]).shape) -> 1, shape=(1,)
len(numpy.array([[1,2,3],[4,5,6]]).shape) -> 2, shape=(2,3)

Is there any other way to get dimensions invariant to the type of the array?

Here is an example of the problem I encounter quite often:

mat3D = np.arange(27).reshape(3,3,3)
mat2D = np.arange(9)

def processMatrix(mat):
  if M.ndim == 2:
    return foo(mat)
  else:
    return np.array([foo(mat[:,:,c]) for c in range(mat.shape[2])]) 

Having mat2D.shape = (3,3,1) would simplify the code to:

def processMatrix(mat):
    return np.array([foo(mat[:,:,c]) for c in range(mat.shape[2])]) 
9
  • numpy.array([[1,2,3]]).shape return (1,3) Commented Jul 30, 2014 at 19:45
  • 1
    The shape tuple has to change size, to match the number of dimensions. If you have N dimensions, you need N numbers to specify the size. Could you be more specific about what you find annoying about this? Maybe your real issue is different from what it seems. Commented Jul 30, 2014 at 19:47
  • Numpy arrays can have N dimensions. E.g. np.array([[[1,2],[3,4]],[[5,6],[7,8]]]).shape is (2,2,2). The "invariant" is that a.ndim is len(a.shape). Commented Jul 30, 2014 at 20:00
  • @DSM I often find myself to use both 1D and 2D arrays interchangeably and the shape tuple changing size requires unnecessary if-else conditions. I guess I should just wrap everything into matrices. Unfortunately most of the functions returns arrays independently from the type of the input. Commented Jul 30, 2014 at 20:01
  • Give an example of one of your unnecessary if-else conditions. Maybe there is another way to handle it. Commented Jul 30, 2014 at 20:04

1 Answer 1

1

You can use

numpy.array([[1,2,3],[4,5,6]]).ndim
Sign up to request clarification or add additional context in comments.

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.