numpy 数组连接:“ValueError:所有输入数组必须具有相同的维数"; [英] numpy array concatenate: "ValueError: all the input arrays must have same number of dimensions"

查看:63
本文介绍了numpy 数组连接:“ValueError:所有输入数组必须具有相同的维数";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何连接这些 numpy 数组?

How to concatenate these numpy arrays?

第一个 np.array 形状为 (5,4)

[[  6487    400 489580      0]
 [  6488    401 492994      0]
 [  6491    408 489247      0]
 [  6491    408 489247      0]
 [  6492    402 499013      0]]

第二个 np.array 形状为 (5,)

[  16.   15.   12.  12.  17. ]

最终结果应该是

[[  6487    400    489580    0   16]
 [  6488    401    492994    0   15]
 [  6491    408    489247    0   12]
 [  6491    408    489247    0   12]
 [  6492    402    499013    0   17]]

我试过 np.concatenate([array1, array2])但我收到此错误

I tried np.concatenate([array1, array2]) but i get this error

ValueError: 所有输入数组的维数必须相同

我做错了什么?

推荐答案

要使用 np.concatenate,我们需要将第二个数组扩展为 2D 然后沿连接axis=1 -

To use np.concatenate, we need to extend the second array to 2D and then concatenate along axis=1 -

np.concatenate((a,b[:,None]),axis=1)

或者,我们可以使用处理它的 np.column_stack -

Alternatively, we can use np.column_stack that takes care of it -

np.column_stack((a,b))

样品运行 -

In [84]: a
Out[84]: 
array([[54, 30, 55, 12],
       [64, 94, 50, 72],
       [67, 31, 56, 43],
       [26, 58, 35, 14],
       [97, 76, 84, 52]])

In [85]: b
Out[85]: array([56, 70, 43, 19, 16])

In [86]: np.concatenate((a,b[:,None]),axis=1)
Out[86]: 
array([[54, 30, 55, 12, 56],
       [64, 94, 50, 72, 70],
       [67, 31, 56, 43, 43],
       [26, 58, 35, 14, 19],
       [97, 76, 84, 52, 16]])

如果 b 是这样的,它是 dtype=object1D 数组,形状为 (1,),很可能所有数据都包含在其中的唯一元素中,我们需要在连接之前展平它.为此,我们也可以在其上使用 np.concatenate.这是一个示例运行,以明确这一点 -

If b is such that its a 1D array of dtype=object with a shape of (1,), most probably all of the data is contained in the only element in it, we need to flatten it out before concatenating. For that purpose, we can use np.concatenate on it too. Here's a sample run to make the point clear -

In [118]: a
Out[118]: 
array([[54, 30, 55, 12],
       [64, 94, 50, 72],
       [67, 31, 56, 43],
       [26, 58, 35, 14],
       [97, 76, 84, 52]])

In [119]: b
Out[119]: array([array([30, 41, 76, 13, 69])], dtype=object)

In [120]: b.shape
Out[120]: (1,)

In [121]: np.concatenate((a,np.concatenate(b)[:,None]),axis=1)
Out[121]: 
array([[54, 30, 55, 12, 30],
       [64, 94, 50, 72, 41],
       [67, 31, 56, 43, 76],
       [26, 58, 35, 14, 13],
       [97, 76, 84, 52, 69]])

这篇关于numpy 数组连接:“ValueError:所有输入数组必须具有相同的维数";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆