Adding a row to a numpy array: 'numpy.ndarray' object has no attribute 'append' or 'vstack'

StackOverflow https://stackoverflow.com/questions/23365893

  •  11-07-2023
  •  | 
  •  

Pregunta

I have a 2D numpy array to which I want to append rows at the end.

I've tried both append and vstack but either way I get an error like:

'numpy.ndarray' object has no attribute 'vstack'

or it says there no attribute append...

This is my code:

g = np.zeros([m, no_features])
# then somewhere in the middle of a for-loop I build a new array called temp_g
# and try to append it to g. temp_g is a 2D array
g.vstack((temp_g,g))

I did g.append(temp_g) but no difference, I get the same error saying there's no such attribute.

Is there something wrong in the way I first declared the array g?

¿Fue útil?

Solución

>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> b = np.array([5, 6, 7])
>>> np.vstack(a, b)   
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: vstack() takes exactly 1 argument (2 given)
>>> 
>>> np.vstack((a, b))
array([[1, 2, 3],
       [5, 6, 7]])

Otros consejos

vstack is a numpy function which takes only a single argument in the form of a tuple . You need to call it and assign the output to your variable. So instead of
g.vstack((temp_g,g))
use
g=np.vstack((temp_g,g))

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top