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])])
shapetuple 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.np.array([[[1,2],[3,4]],[[5,6],[7,8]]]).shapeis(2,2,2). The "invariant" is thata.ndimislen(a.shape).