Initialize numpy array of size N with arrays of size M

I am looking to create a numpy array that looks something like this

N=4
M=3
my_array = np.zeros(...) # or np.full, np.ones...
print(my_array)
>>> [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] # Array of 4 arrays with 3 elements

The elements don’t need to be zero I am just trying to initialize an array in this structure. I do not want to use lists or tuples.

I’ve tried something like this

N=4
M=3
kg_neurons1 = np.full(shape=4,fill_value=np.zeros(M))

But this raises ValueError: could not broadcast input array from shape (3,) into shape (4,)

Any suggestions?

>Solution :

To create a NumPy array with a specific shape, you can use the np.zeros function and pass the desired shape as a tuple. In your case, you want an array with 4 rows and 3 columns, so you can do the following:

import numpy as np

N = 4
M = 3
my_array = np.zeros((N, M))

print(my_array)

This will produce the output:

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

This creates a NumPy array with 4 rows and 3 columns, initialized with zeros.

Leave a Reply