Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading