【问题标题】:Concatenate two arrays into a new array将两个数组连接成一个新数组
【发布时间】:2021-09-20 00:53:43
【问题描述】:

我有两个数组,

A = np.array([[1,2,3],[4,5,6]])
b = np.array([100,101])

我想将它们连接起来,以便在右侧添加一列 b,这样我们就有了一个新数组 A | b,它类似于:

1 2 3 100

4 5 6 101

我正在尝试以这种方式连接:

new = np.concatenate((A, b), axis=1)

但我得到下一个错误:

ValueError: all the input arrays must have the same number of dimensions, but the array at index 0 has 2 dimension(s), and the array at index 1 has 1 dimension(s)

如何连接这两个数组?

【问题讨论】:

  • 你了解数组的shape,以及它们各自的维数吗?

标签: python arrays numpy concatenation


【解决方案1】:

你可以使用column_stack:

>>> np.column_stack((A, b))

array([[  1,   2,   3, 100],
       [  4,   5,   6, 101]])

它负责 b 不是 2D。


为了使concatenate 工作,我们手动使b 形状为(2, 1)

>>> np.concatenate((A, b[:, np.newaxis]), axis=1)

array([[  1,   2,   3, 100],
       [  4,   5,   6, 101]])

【讨论】:

    【解决方案2】:

    你也可以 Transpose A 做一个垂直堆栈,然后将其转回np.vstack((A.T,b)).T

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-29
      • 1970-01-01
      • 2011-06-19
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      • 2021-05-19
      • 1970-01-01
      相关资源
      最近更新 更多