繁体   English   中英

Python 将一维数组逐列添加到二维数组

[英]Python add 1d array to 2d array by column

我有一个一维数组和一个二维数组

a = [4,7,10]
b = [[1,2,3],[4,5,6],[7,8,9]]
a.shape = (2,)
b.shape = (3,3)

我想:

c = [[1,2,3,4],[4,5,6,7],[7,8,9,10]]
c.shape = (3,4)

我试过np.vstacknp.concenrate但都失败了

您可以使用numpy.column_stack

>>> np.column_stack([b,a])
array([[ 1,  2,  3,  4],
       [ 4,  5,  6,  7],
       [ 7,  8,  9, 10]])

当您尝试某事并失败时,您应该显示工作和错误。 你可能会在这个过程中学到一些东西。

In [19]: a = np.array([4,7,10])
    ...: b = np.array([[1,2,3],[4,5,6],[7,8,9]])
In [20]: np.vstack((a,b))
Out[20]: 
array([[ 4,  7, 10],
       [ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9]])

顾名思义, vstack可以工作,但垂直添加。

要水平连接它们,我们需要指定轴 1:

In [28]: np.concatenate((b,a), axis=1)
Traceback (most recent call last):
  File "<ipython-input-28-52d167b3d573>", line 1, in <module>
    np.concatenate((b,a), axis=1)
  File "<__array_function__ internals>", line 5, in concatenate
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)

vstack垂直连接它们(轴 0),并根据需要调整尺寸。

但是很容易a . reshape可以做到,还有:

In [29]: a[:,None].shape
Out[29]: (3, 1)

In [30]: np.concatenate((b,a[:,None]), axis=1)
Out[30]: 
array([[ 1,  2,  3,  4],
       [ 4,  5,  6,  7],
       [ 7,  8,  9, 10]])

如果您按照其他答案中的建议查看column_stack的代码,您会看到它这样做 - 根据需要添加尺寸。

核心 join function 是concatenate 学习调整尺寸,您可以在不记住所有不同名称的情况下进行各种连接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM