Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building up an array in numpy/scipy by iteration in Python?

Often, I am building an array by iterating through some data, e.g.:

my_array = []
for n in range(1000):
  # do operation, get value 
  my_array.append(value)
# cast to array
my_array = array(my_array)

I find that I have to first build a list and then cast it (using "array") to an array. Is there a way around these? All these casting calls clutter the code... how can I iteratively build up "my_array", with it being an array from the start?


1 Answers

NumPy provides a 'fromiter' method:

def myfunc(n):
    for i in range(n):
        yield i**2


np.fromiter(myfunc(5), dtype=int)

which yields

array([ 0,  1,  4,  9, 16])
like image 130
Stefan van der Walt Avatar answered Sep 12 '25 09:09

Stefan van der Walt