如何修复:所有输入数组必须有相同的维数

584 阅读2分钟

你在使用NumPy时可能遇到的一个错误是:

ValueError: all the input arrays must have same number of dimensions

当你试图串联两个尺寸不同的NumPy数组时,会出现这个错误。

下面的例子展示了如何在实践中解决这个错误。

如何重现该错误

假设我们有以下两个NumPy数组:

import numpy as np

#create first array
array1 = np.array([[1, 2], [3, 4], [5,6], [7,8]])

print(array1) 

[[1 2]
 [3 4]
 [5 6]
 [7 8]]

#create second array 
array2 = np.array([9,10, 11, 12])

print(array2)

[ 9 10 11 12]

现在假设我们试图使用**concatenate()**函数将这两个数组合并成一个数组:

#attempt to concatenate the two arrays
np.concatenate([array1, array2])

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)

我们收到一个ValueError,因为这两个数组有不同的尺寸。

如何修复这个错误

我们可以用两种方法来解决这个错误。

方法1:使用np.column_stack

在避免错误的同时连接两个数组的一个方法是使用column_stack()函数,如下所示:

np.column_stack((array1, array2))

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

注意,我们能够成功地连接这两个数组而没有任何错误。

方法2:使用np.c_

我们也可以使用np.c_函数来连接两个数组,同时避免错误,如下所示:

np.c_[array1, array2]

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

请注意,这个函数返回的结果与前面的方法完全相同。

其他资源

下面的教程解释了如何修复Python中的其他常见错误:

如何修复Pandas中的KeyError
如何修复ValueError: 无法将浮点数NaN转换为整数
如何修复ValueError:操作数不能与形状一起广播