Home > Software engineering >  How to add multiple values to numpy array
How to add multiple values to numpy array

Time:05-24

I have a list:

[1, 2, 3]

How do I add it to a numpy array like this?

[[1, 2, 3]
[4, 5, 6]]

So it becomes:

[[2, 4 6]
[5, 7, 9]]

CodePudding user response:

import numpy as np
a = np.array([1, 2, 3])
b = np.array([[1, 2, 3],
              [4, 5, 6]])

print(a b)

Result

[[2 4 6]
 [5 7 9]]

Explanation, that's how broadcasting works.

  • Take first dimension of the bigger matrix b
  • Add row by row the lower dimension vector a

CodePudding user response:

Please find the example code snippet below.

import numpy as np

list_1 = [1, 2, 3]
numpy_array_1 = np.array([[1, 2, 3], [4, 5, 6]])

print("List = ", list_1)
print("Numpy Array = \n", numpy_array_1)
print("List added to the Numpy Array = \n", list_1   numpy_array_1)
  • Related