Reputation: 7564
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])])
Upvotes: 1
Views: 576