how to append a 1d numpy array to a 2d numpy array python

Viewed 723

I would like to append an array [3, 3, 3] to an array [[1, 1, 1], [2, 2, 2]], so that it becomes [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

Here is my code:

import numpy as np
arr1 = np.array([[1, 1, 1], 
                 [2, 2, 2]])

arr2 = np.append(arr1, [3, 3, 3])

print (arr2)

instead of printing [[1, 1, 1], [2, 2, 2], [3, 3, 3]],

it prints [1, 1, 1, 2, 2, 2, 3, 3, 3].

I am quite new to numpy and I do not understand why the 2d array suddenly becomes 1d.

3 Answers

You can use the useful numpy's standard method of vstack.

Here is my code.

Initialize 2-dimensional numpy array

initial_array = np.array([
    [1, 1, 1], 
    [2, 2, 2]
])

define the array to append to initiali array

new_array = np.array([3, 3, 3])

append the new array to initial array as row

result = np.vstack((initial_array, new_array))

this is the result

print(result)
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])

You can read more details at here.

Hope this answer to be helpful for you. Thanks.

import numpy as np
arr1 = np.array([[1, 1, 1], 
                 [2, 2, 2]])

arr2 = np.append(arr1, [[3, 3, 3]], axis=0)

print (arr2)

Output:

[[1 1 1]                                                                                                                                                                                                        
 [2 2 2]                                                                                                                                                                                                        
 [3 3 3]] 

Use numpy.vstack:

arr2 = np.vstack((arr1, [3,3,3]))
>>> arr2
[[1 1 1]
 [2 2 2]
 [3 3 3]]
Related