Curious2learn - 10 months ago 95

Python Question

Is there way to initialize a numpy array of a shape and add to it? I will explain what I need with a list example. If I want to create a list of objects generated in a loop, I can do:

`a = []`

for i in range(5):

a.append(i)

I want to do something similar with a numpy array. I know about vstack, concatenate etc. However, it seems these require two numpy arrays as inputs. What I need is:

`big_array # Initially empty. This is where I don't know what to specify`

for i in range(5):

array i of shape = (2,4) created.

add to big_array

The

`big_array`

`(10,4)`

`big_array = numpy.zeros((10,4))`

`.append`

Answer

Return a new array of given shape and type, filled with zeros.

or

Return a new array of given shape and type, filled with ones.

or

Return a new array of given shape and type, without initializing entries.

However, the mentality in which we construct an array by appending elements to a list is not much used in numpy, because it's less efficient (numpy datatypes are much closer to the underlying C arrays). Instead, you should preallocate the array to the size that you need it to be, and then fill in the rows. You can use `numpy.append`

if you must, though.

Source (Stackoverflow)