繁体   English   中英

"如何附加 np.array?"

[英]How to append np.array?

我有一个 (3,6) 的 np.array d1<\/code>和一个 (1,6) 的 np.array a4<\/code> 。

如何组合两个 np.array 以形成 (4,6) 的 np.array d2<\/code> ?

我的代码如下:

import numpy as np
a1=np.array(range(6))
a2=a1+2
a3=a2+3
a4=a3+4
d1=np.array([a1,a2,a3])
d1.shape

我相信https:\/\/numpy.org\/doc\/stable\/reference\/generated\/numpy.concatenate.html<\/a> concatenate 是您正在寻找的命令。

foo = np.array([[1,2,3],
                [4,5,6]])
bar = np.array([7,8,9])

# axis 0 will combine rows, axis 1 will combine columns
foobar = numpy.concatenate(foo,bar,axis = 0)

array([[1,2,3],
       [4,5,6],
       [7,8,9]])

首先,您需要重塑当前形状为(6,)<\/code>的 a4

a4 = a4.reshape(1,-1)  # shape=(1,6)

a4 是一维数组,所以你可以扩展它

import numpy as np 

d1 = np.array([[ 0,  1,  2,  3,  4,  5],
               [ 2,  3,  4,  5,  6,  7],
               [ 5,  6,  7,  8,  9, 10]])

a4 = np.array(np.arange(9,15))

d2 = np.concatenate((d1, np.expand_dims(a4,0)), 0)

print(d2)

这可能会令人费解,但是:

In [156]: d1.shape
Out[156]: (3, 6)
In [157]: a4.shape
Out[157]: (6,)               # not (1,6)
In [158]: np.append(d1,a4)
Out[158]: 
array([ 0,  1,  2,  3,  4,  5,  2,  3,  4,  5,  6,  7,  5,  6,  7,  8,  9,
       10,  9, 10, 11, 12, 13, 14])

np.append说它会使数组变平,除非我们提供一个axis

In [159]: np.append(d1,a4, axis=0)
Traceback (most recent call last):
  File "<ipython-input-159-dd72c66fd0c0>", line 1, in <module>
    np.append(d1,a4, axis=0)
  File "<__array_function__ internals>", line 180, in append
  File "/usr/local/lib/python3.8/dist-packages/numpy/lib/function_base.py", line 5392, in append
    return concatenate((arr, values), axis=axis)
  File "<__array_function__ internals>", line 180, in concatenate
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

请注意, append调用np.concatenate 这就是它真正的作用。 np.append应该被删除——它误导了太多的新手。

无论如何, concatenate期望数组在维数上匹配。 错误应该清楚地说明问题。 正如其他答案所示,解决方案是将(6,)变成(1,6)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM