简体   繁体   English

连接两个不同尺寸的arrays numpy

[英]Concat two arrays of different dimensions numpy

I am trying to concatenate two numpy arrays to add an extra column: array_1 is (569, 30) and array_2 is is (569, )我正在尝试连接两个 numpy arrays 添加一个额外的列: array_1 is (569, 30) and array_2 is (569, )

combined = np.concatenate((array_1, array_2), axis=1)

I thought this would work if I set axis=2 so it will concatenate vertically.我认为如果我设置axis=2这将起作用,因此它将垂直连接。 The end should should be a 569 x 31 array.最后应该是一个 569 x 31 的数组。

The error I get is ValueError: all the input arrays must have same number of dimensions我得到的错误是ValueError: all the input arrays must have same number of dimensions

Can someone help?有人可以帮忙吗?

Thx!谢谢!

You can use numpy.column_stack :您可以使用numpy.column_stack

np.column_stack((array_1, array_2))

Which converts the 1-d array to 2-d implicitly, and thus equivalent to np.concatenate((array_1, array_2[:,None]), axis=1) as commented by @umutto. np.concatenate((array_1, array_2[:,None]), axis=1)一维数组隐式转换为np.concatenate((array_1, array_2[:,None]), axis=1)数组,因此相当于np.concatenate((array_1, array_2[:,None]), axis=1)


a = np.arange(6).reshape(2,3)
b = np.arange(2)

a
#array([[0, 1, 2],
#       [3, 4, 5]])

b
#array([0, 1])

np.column_stack((a, b))
#array([[0, 1, 2, 0],
#       [3, 4, 5, 1]])

要垂直堆叠它们,请尝试 np.vstack((array1,array2))

You can convert the 1-D array to 2-D array with the same number of rows using reshape function and concatenate the resulting array horizontally using numpy's append function.您可以使用 reshape function 将一维数组转换为具有相同行数的二维数组,并使用 numpy 的 append ZC1C425268E68385D1AB54Z507F 水平连接生成的数组。

Note: In numpy's append function, we have to mention axis along which we want to insert the values.注意:在 numpy 的 append function 中,我们必须提到要插入值的轴。 If axis=0, arrays are appended vertically.如果axis=0,则垂直附加arrays。 If axis=1, arrays are appended horizontally.如果axis=1,则水平附加arrays。 So, we can use axis=1, for current requirement因此,我们可以使用axis = 1来满足当前需求

eg例如

a = np.arange(6).reshape(2,3)
b = np.arange(2)

a
#array([[0, 1, 2],
#       [3, 4, 5]])

b
#array([0, 1])

#First step, convert this 1-D array to 2-D (Number of rows should be same as array 'a' i.e. 2)
c = b.reshape(2,1)

c
#array([[0],
        [1]])


#Step 2, Using numpy's append function we can concatenate both arrays with same number of rows horizontally

requirement = np.append((a, c, axis=1))

requirement
#array([[0, 1, 2, 0],
#       [3, 4, 5, 1]])

You can simply use numpy 's hstack function.您可以简单地使用numpyhstack函数。

eg例如

import numpy as np

combined = np.hstack((array1,array2))

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

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