Add a new axis if a numpy array is 1D, to convert it into 2D (shape: (1, n)) without if conditions

Viewed 38

I want to write a code that will use a numpy array that can be 1D array or 2D. For avoiding related errors due to incompatibility of the array shapes with the code body, I want to convert 1D array to 2D if it was 1D, So if:

arr1 = np.array([2, 1, 4])                  # shape: (3,)
arr2 = np.array([[2, 1, 4], [1, 3, 11]])    # shape: (2,3)

I am seeking for a way, if there is, that the code automatically detect the shapes and convert that to the desired one (1, n) if that was 1D, without external if conditions (e.g. with some numpy reshaping repeatedly or …):

arr1 = np.array([[2, 1, 4]])                # shape: (1,3)   <-- modified
arr2 = np.array([[2, 1, 4], [1, 3, 11]])    # shape: (2,3)   it is not modified

I know it can be achieved easily with if condition in 2 lines, but I am curious if it can be handled by numpy itself:

if arr.ndim == 1:
    arr= arr[None, :]      # --> shape = (1, n)

Also, I would appreciate for any opinion about is it preferable to use this way instead if condition?

0 Answers
Related