【发布时间】:2021-10-12 13:27:51
【问题描述】:
我想在数组[[1, 1, 1], [2, 2, 2]]上追加一个数组[3, 3, 3],这样就变成了[[1, 1, 1] , [2, 2, 2], [3, 3, 3]]
这是我的代码:
import numpy as np
arr1 = np.array([[1, 1, 1],
[2, 2, 2]])
arr2 = np.append(arr1, [3, 3, 3])
print (arr2)
而不是打印[[1, 1, 1], [2, 2, 2], [3, 3, 3]],
它打印[1, 1, 1, 2, 2, 2, 3, 3, 3]。
我对 numpy 很陌生,我不明白为什么 2d 数组突然变成 1d。
【问题讨论】:
-
您回去阅读
np.append文档了吗?它解释了扁平化。 -
是的,它说你必须使用参数 ``axis=0``` 。我尝试这样做:
arr2 = np.append(arr1, [3, 3, 3], axis=0),它给了我错误: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) -
np.append基本上是调用np.concatenate的另一种方式,正如对错误的回溯所示。一个数组是 (2,3) 形状,另一个是 (3,)。第二个应该是 (1,3) 形状来连接。vstack是concatenate的替代用户,负责处理该细节。