ValueError:所有输入数组的维数必须相同

发布于 2021-01-29 15:06:39

我有一个问题np.append

我正在尝试n_list_converted通过使用以下代码来复制20x361矩阵的最后一列:

n_last = []
n_last = n_list_converted[:, -1]
n_lists = np.append(n_list_converted, n_last, axis=1)

但是我得到了错误:

ValueError:所有输入数组的维数必须相同

但是,我已经通过检查矩阵尺寸

 print(n_last.shape, type(n_last), n_list_converted.shape, type(n_list_converted))

我得到

(20公升)(20公升,361公升)

所以尺寸匹配?错误在哪里?

关注者
0
被浏览
81
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    如果我从3x4数组开始,然后将3x1数组与轴1连接起来,则会得到3x5数组:

    In [911]: x = np.arange(12).reshape(3,4)
    In [912]: np.concatenate([x,x[:,-1:]], axis=1)
    Out[912]: 
    array([[ 0,  1,  2,  3,  3],
           [ 4,  5,  6,  7,  7],
           [ 8,  9, 10, 11, 11]])
    In [913]: x.shape,x[:,-1:].shape
    Out[913]: ((3, 4), (3, 1))
    

    请注意,两个要连接的输入都具有2维。

    省略形状:,并且x[:,-1]为(3,)形状-为1d,因此出现错误:

    In [914]: np.concatenate([x,x[:,-1]], axis=1)
    ...
    ValueError: all the input arrays must have same number of dimensions
    

    的代码np.append是(在这种情况下,指定了轴)

    return concatenate((arr, values), axis=axis)
    

    因此,只需稍稍更改语法即可append。它使用2个参数代替列表。它模仿列表append是语法,但不应与该列表方法混淆。

    In [916]: np.append(x, x[:,-1:], axis=1)
    Out[916]: 
    array([[ 0,  1,  2,  3,  3],
           [ 4,  5,  6,  7,  7],
           [ 8,  9, 10, 11, 11]])
    

    np.hstack首先确保所有输入均为atleast_1d,然后进行串联:

    return np.concatenate([np.atleast_1d(a) for a in arrs], 1)
    

    因此,它需要相同的x[:,-1:]输入。本质上是相同的动作。

    np.column_stack 在轴1上也进行连接。但是首先它将1d输入通过

    array(arr, copy=False, subok=True, ndmin=2).T
    

    这是将(3,)数组转换为(3,1)数组的一般方法。

    In [922]: np.array(x[:,-1], copy=False, subok=True, ndmin=2).T
    Out[922]: 
    array([[ 3],
           [ 7],
           [11]])
    In [923]: np.column_stack([x,x[:,-1]])
    Out[923]: 
    array([[ 0,  1,  2,  3,  3],
           [ 4,  5,  6,  7,  7],
           [ 8,  9, 10, 11, 11]])
    

    所有这些“堆栈”都可以方便使用,但从长远来看,了解尺寸和基础很重要np.concatenate。还知道如何查找类似这样的函数的代码。我经常使用ipython
    ??魔术。

    在时间测试中,np.concatenate速度明显更快-像这样的小数组,额外的函数调用层会产生很大的时差。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看