Home > Software engineering >  Defining empty numpy array when we do not know the size
Defining empty numpy array when we do not know the size

Time:10-19

From my understanding, when we want to define a numpy array, we have to define its size.

However, in my case, I want to define a numpy array and then extend it based on my values in the for loop. The shape of values might differ in each run. So I cannot define the numpy array shape in advance.

Is there any way to overcome this?

I would like to avoid using lists.

Thanks

CodePudding user response:

I think numpy array is just like array in clang or c , I mean when you make numpy array you allocate memory depend on your request(size and dtype). So it is better to make array after the size of array is determinated.

Or you can try numpy.append https://numpy.org/doc/stable/reference/generated/numpy.append.html But I don't think it is preferable way because it keeps generate new arrays.

CodePudding user response:

import numpy as np  
myArrayShape = 2
myArray = np.empty(shape=2)

Note that this generates random values for each element in the array.

  • Related