Home > Net >  Storing multiple arrays in a np.zeros or np.ones
Storing multiple arrays in a np.zeros or np.ones

Time:11-14

I'm trying to initialize a dummy array of length n using np.zeros(n) with dtype=object. I want to use this dummy array to store n copies of another array of length m. I'm trying to avoid for loop to set values at each index.

I tried using the below code but keep getting error -

temp = np.zeros(10, dtype=object)
arr = np.array([1.1,1.2,1.3,1.4,1.5])
res = temp * arr

The desired result should be -

np.array([[1.1,1.2,1.3,1.4,1.5], [1.1,1.2,1.3,1.4,1.5], ... 10 copies])

I keep getting the error -

operands could not be broadcast together with shapes (10,) (5,) 

I understand that this error arises since the compiler thinks I'm trying to multiply those arrays. So how do I achieve the task?

CodePudding user response:

np.tile() is a built-in function that repeats a given array reps times. It looks like this is exactly what you need, i.e.:

res = np.tile(arr, 2)

CodePudding user response:

>>> arr = np.array([1.1,1.2,1.3,1.4,1.5])
>>> arr
array([1.1, 1.2, 1.3, 1.4, 1.5])
>>> np.array([arr]*10)

array([[1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5],
        [1.1, 1.2, 1.3, 1.4, 1.5]])
  • Related