向 numpy 数组添加行:'numpy.ndarray'对象没有属性'append'或'vstack'



我有一个2D numpy数组,我想在其末尾添加行。

我已经尝试了appendvstack,但无论哪种方式,我都会得到一个错误,比如:

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

或者说没有属性append。。。

这是我的代码:

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))

我做了g.append(temp_g),但没有区别,我得到了同样的错误,说没有这样的属性。

我第一次声明数组g的方式有什么问题吗?

>>> 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]])
vstack是一个numpy函数,它只接受元组形式的单个参数。您需要调用它并将输出分配给您的变量。所以不是
g.vstack((temp_g,g))
使用
g=np.vstack((temp_g,g))

最新更新