简体   繁体   English

Numpy 将二维数组与一维数组连接起来

[英]Numpy concatenate 2D arrays with 1D array

I am trying to concatenate 4 arrays, one 1D array of shape (78427,) and 3 2D array of shape (78427, 375/81/103).我正在尝试连接 4 个数组,一个一维形状数组 (78427,) 和 3 个二维形状数组 (78427, 375/81/103)。 Basically this are 4 arrays with features for 78427 images, in which the 1D array only has 1 value for each image.基本上这是 4 个具有 78427 个图像特征的数组,其中一维数组每个图像只有 1 个值。

I tried concatenating the arrays as follows:我尝试按如下方式连接数组:

>>> print X_Cscores.shape
(78427, 375)
>>> print X_Mscores.shape
(78427, 81)
>>> print X_Tscores.shape
(78427, 103)
>>> print X_Yscores.shape
(78427,)
>>> np.concatenate((X_Cscores, X_Mscores, X_Tscores, X_Yscores), axis=1)

This results in the following error:这会导致以下错误:

Traceback (most recent call last): File "", line 1, in ValueError: all the input arrays must have same number of dimensions回溯(最近一次调用):文件“”,第 1 行,在 ValueError 中:所有输入数组必须具有相同的维数

The problem seems to be the 1D array, but I can't really see why (it also has 78427 values).问题似乎是一维数组,但我真的不明白为什么(它也有 78427 个值)。 I tried to transpose the 1D array before concatenating it, but that also didn't work.我试图在连接它之前转置一维数组,但这也不起作用。

Any help on what's the right method to concatenate these arrays would be appreciated!任何关于连接这些数组的正确方法的帮助将不胜感激!

Try concatenating X_Yscores[:, None] (or X_Yscores[:, np.newaxis] as imaluengo suggests).尝试连接X_Yscores[:, None] (或X_Yscores[:, np.newaxis]正如imaluengo 建议的那样)。 This creates a 2D array out of a 1D array.这将从一维数组中创建一个二维数组。

Example:例子:

A = np.array([1, 2, 3])
print A.shape
print A[:, None].shape

Output:输出:

(3,)
(3,1)

I am not sure if you want something like:我不确定你是否想要这样的东西:

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

c = a.ravel()
con = np.concatenate( (c,b ) )

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

OR或者

np.column_stack( (a,b) )

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

np.row_stack( (a,b) )

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

You can try this one-liner:你可以试试这个单线:

concat = numpy.hstack([a.reshape(dim,-1) for a in [Cscores, Mscores, Tscores, Yscores]])

The "secret" here is to reshape using the known, common dimension in one axis, and -1 for the other, and it automatically matches the size (creating a new axis if needed).这里的“秘密”是在一个轴上使用已知的通用尺寸进行重塑,而在另一个轴上使用 -1,并且它会自动匹配大小(如果需要,创建一个新轴)。

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

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