我有一个numpy_array.有点像[ a b c ].
然后我想将它附加到另一个NumPy数组中(就像我们创建一个列表列表一样).我们如何创建包含NumPy数组的NumPy数组数组?
我试着做下面没有任何运气
>>> M = np.array([])
>>> M
array([], dtype=float64)
>>> M.append(a,axis=0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'append'
>>> a
array([1, 2, 3])
Run Code Online (Sandbox Code Playgroud)
end*_*ith 165
In [1]: import numpy as np
In [2]: a = np.array([[1, 2, 3], [4, 5, 6]])
In [3]: b = np.array([[9, 8, 7], [6, 5, 4]])
In [4]: np.concatenate((a, b))
Out[4]:
array([[1, 2, 3],
[4, 5, 6],
[9, 8, 7],
[6, 5, 4]])
Run Code Online (Sandbox Code Playgroud)
或这个:
In [1]: a = np.array([1, 2, 3])
In [2]: b = np.array([4, 5, 6])
In [3]: np.vstack((a, b))
Out[3]:
array([[1, 2, 3],
[4, 5, 6]])
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 54
好吧,错误消息说明了一切:NumPy数组没有append()方法.numpy.append()但是有一个免费的功能:
numpy.append(M, a)
Run Code Online (Sandbox Code Playgroud)
这将创建一个新数组而不是变异M.请注意,使用numpy.append()涉及复制两个数组.如果使用固定大小的NumPy数组,您将获得更好的代码.
小智 23
你可以用numpy.append()......
import numpy
B = numpy.array([3])
A = numpy.array([1, 2, 2])
B = numpy.append( B , A )
print B
> [3 1 2 2]
Run Code Online (Sandbox Code Playgroud)
这不会创建两个单独的数组,但会将两个数组附加到一个单维数组中.
luk*_*ell 10
Sven说了这一切,因为在调用append时自动调整类型,所以要非常谨慎.
In [2]: import numpy as np
In [3]: a = np.array([1,2,3])
In [4]: b = np.array([1.,2.,3.])
In [5]: c = np.array(['a','b','c'])
In [6]: np.append(a,b)
Out[6]: array([ 1., 2., 3., 1., 2., 3.])
In [7]: a.dtype
Out[7]: dtype('int64')
In [8]: np.append(a,c)
Out[8]:
array(['1', '2', '3', 'a', 'b', 'c'],
dtype='|S1')
Run Code Online (Sandbox Code Playgroud)
正如您所看到的那样,dtype从int64变为float32,然后变为S1
实际上,人们总是可以创建一个普通的 numpy 数组列表,然后再进行转换。
In [1]: import numpy as np
In [2]: a = np.array([[1,2],[3,4]])
In [3]: b = np.array([[1,2],[3,4]])
In [4]: l = [a]
In [5]: l.append(b)
In [6]: l = np.array(l)
In [7]: l.shape
Out[7]: (2, 2, 2)
In [8]: l
Out[8]:
array([[[1, 2],
[3, 4]],
[[1, 2],
[3, 4]]])
Run Code Online (Sandbox Code Playgroud)
小智 6
我在寻找稍微不同的东西时找到了此链接,如何开始将数组对象附加到空的 numpy数组,但是尝试了此页上的所有解决方案,但无济于事。
然后我找到了这个问题和答案:如何向空的numpy数组添加新行
要点:
“启动”所需阵列的方法是:
arr = np.empty((0,3), int)
然后,您可以使用串联添加行,如下所示:
arr = np.concatenate( ( arr, [[x, y, z]] ) , axis=0)
另请参阅https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html