-2

I am trying to iteratively add rows to my two dimensional np.array

A = np.zeros((1,14),dtype = float)
for i in arr:
    A = np.vstack(fn(i))# function returns array 
    

And as a result i always get only last array i stacked Can someone please explain me how to stack all rows and why is this not working

programer
  • 3
  • 3
  • Does this answer your question? [Concatenate all rows of a numpy matrix in python](https://stackoverflow.com/questions/13252781/concatenate-all-rows-of-a-numpy-matrix-in-python) – tornikeo Sep 07 '20 at 07:29

2 Answers2

1

You should not vstack while iterating, as it will artificially increase memory usage, as explained in this similar question but related to pandas.

Secondly, assuming fn(i) returns a new array that you want to append to A, then that line should be A = np.vstack((A, fn(i))

Considering all this, a better option would be to create and collect all your arrays into a list that you can later stack.

A = np.zeros((1, 14), dtype=float)
arrays = [A] + [fn(i) for i in arr] # assuming `arr` is an iterable
A = np.vstack(tuple(arrays))

You can read more in the numpy.vstack docs

RichieV
  • 5,103
  • 2
  • 11
  • 24
0

You must add A on vstack:

A = np.zeros((1,14),dtype = float)
for i in arr:
    A = np.vstack([A,fn(i)])# function returns array 
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30