Home > Software engineering >  Appending 1D Ndarray to 2D Ndarray
Appending 1D Ndarray to 2D Ndarray

Time:01-22

I'm attempting to append a 1D array which have generated by appending elements one at a time to a 2D array as a new row in the array.

    a = np.ones((2, 5), int)
    b = np.empty((0, 5), int)

    b = np.append(b, [1])
    b = np.append(b, [2])
    b = np.append(b, [3])
    b = np.append(b, [4])
    b = np.append(b, [5])

    a = np.append(a, b, axis=0)

    print(b)

I'm pretty lost as to why this code doesn't work? They are both arrays of 5 elements, but get the following error? "ValueError: all the input arrays must have same number of dimensions"

CodePudding user response:

a and b have different dim a is (2,5) and b is (5,) reshape b to be (1,5).

Then you can append b row-wise as following:

result=np.append(a,b.reshape(1,-1),axis=0)

CodePudding user response:

np.append is trying to concatenate a 1D array (b) with a 2D array (a) along a specific axis, but b doesn't have the same number of dimensions as a.

use vstack instead of append:

b = np.array([1, 2, 3, 4, 5])
a = np.vstack((a, b))
b = np.array([1, 2, 3, 4, 5])
a = np.concatenate((a, b[np.newaxis, :]), axis=0)

In the above examples, b is first reshaped to a 2D array with shape (1,5) and then concatenated to a.

  • Related