Friday, May 13, 2022

[FIXED] how to append a 1d numpy array to a 2d numpy array python

Issue

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.


Solution

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.



Answered By - Dragan Kojić
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.