Python numpy多维数组追加元素出现维度匹配错误如何解决
错误原因
你初始化的difference = np.array([[]])的shape为(1, 0),而每次匹配到的[i]的shape为(1, 2),两个数组在第1维度的长度(0和2)不匹配,因此concatenate调用会抛出维度不一致的错误。
修复方案
方案1:用Python列表暂存结果(更推荐)
循环拼接numpy数组性能极低,用列表暂存结果最后统一转数组的写法更高效,也不会出现维度匹配问题:
import numpy as np a = np.array([[0,12],[1,40],[0,55],[1,23],[0,123.5],[1,4]]) b = np.array([[0,3],[1,10],[0,55],[1,34],[1,122],[0,123]]) # 先用空列表存储匹配到的元素 difference = [] for i in a: for j in b: if np.allclose(i, j, atol=0.5): difference.append(i) # 最后统一转换为numpy数组 difference = np.array(difference) print(difference)
输出符合预期:
[[ 0. 55. ] [ 0. 123.5]]
方案2:修正初始数组维度(适合必须用concatenate的场景)
把difference初始化为shape为(0, 2)的空数组,和后续要拼接的数组维度对齐即可:
import numpy as np a = np.array([[0,12],[1,40],[0,55],[1,23],[0,123.5],[1,4]]) b = np.array([[0,3],[1,10],[0,55],[1,34],[1,122],[0,123]]) # 初始化维度匹配的空numpy数组 difference = np.empty((0, 2)) for i in a: for j in b: if np.allclose(i, j, atol=0.5): difference = np.concatenate((difference, [i])) print(difference)
内容的提问来源于stack exchange,提问作者georgehere
相关产品推荐
相关产品推荐

