Python 连接两个不同维度的数组numpy

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46700081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:46:03  来源:igfitidea点击:

Concat two arrays of different dimensions numpy

pythonnumpy

提问by Trung Tran

I am trying to concatenate two numpy arrays to add an extra column: array_1is (569, 30)and array_2is is (569, )

我正在尝试连接两个 numpy 数组以添加一个额外的列:array_1is(569, 30)array_2is(569, )

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

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

I thought this would work if I set axis=2so it will concatenate vertically. The end should should be a 569 x 31 array.

我认为如果我设置axis=2它会起作用,它会垂直连接。最后应该是一个 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!

谢谢!

回答by Psidom

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)它将一维数组隐式转换为二维数组,因此等效于@umutto 的评论。



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]])

回答by Darshil Shah

You can simply use numpy's hstackfunction.

您可以简单地使用numpyhstack功能。

e.g.

例如

import numpy as np

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