【问题标题】:Adding a row to a numpy array: 'numpy.ndarray' object has no attribute 'append' or 'vstack'向 numpy 数组添加一行:“numpy.ndarray”对象没有属性“append”或“vstack”
【发布时间】:2014-06-15 11:07:42
【问题描述】:

我有一个 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 的方式有问题吗?

【问题讨论】:

  • vstack 是一个 numpy 函数而不是 ndarray 实例方法 np.vstack((g, temp-g))

标签: python arrays numpy append


【解决方案1】:
>>> 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]])

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-12-08
      • 2017-08-14
      • 2019-11-09
      • 1970-01-01
      • 2021-08-29
      • 2019-05-07
      • 2020-01-11
      • 1970-01-01
      • 2012-01-14
      相关资源
      最近更新 更多