简体   繁体   English

无法将2d数组合并为另一个2d数组(python)

[英]unable to combine 2d arrays into another 2d array (python)

I have two lists, 我有两个清单,

    list_a
    list_b

whose shape are [10,50] and [40,50] and I'm trying to combine them into one [50,50] array, starting with the following code (edited for readability) 形状为[10,50]和[40,50]的图形,我尝试将它们组合成一个[50,50]数组,从以下代码开始(针对可读性进行了编辑)

    array_a=np.array(list_a)
    array_b=np.array(list_b)
    array_c=np.concatenate(array_a,array_b)

But it keeps giving me an error that says 但是它一直给我一个错误,说

"TypeError: only length-1 arrays can be converted to Python scalars" “ TypeError:只能将长度为1的数组转换为Python标量”

What's the issue here, and how can I fix it? 这是什么问题,我该如何解决? This error isn't very helpful... 此错误不是很有帮助...

np.concatenate expects a tuple as argument, ie it should be np.concatenate需要一个元组作为参数,即它应该是

array_c=np.concatenate((array_a,array_b))

The first argument is a tuple of an arbitrary number of arrays, the second argument (in your case array_b ) tells concatenate along which axis it should operate. 第一个参数是任意数量的数组的元组,第二个参数(在您的情况下为array_b )告诉concatenate它应该沿着哪个轴进行操作。

The issue here is that np.concatenate expects an iterable sequence of array-like objects for the first argument. 这里的问题是np.concatenate期望第一个参数的数组类对象的可迭代序列。 Here it just takes array_a as the first argument. 在这里,仅将array_a作为第一个参数。 It is taking array_b as the second argument, which specifies which array axis to concatenate along. 它使用array_b作为第二个参数,该参数指定要沿着其连接的数组轴。 As this argument needs to be integer-like, it is attempting to convert array_b to an integer, but failing as it contains more than one item. 由于此参数需要类似于整数,因此它试图将array_b转换为整数,但由于包含多个项而失败。 Hence this error message. 因此,此错误消息。

To solve it, you need to wrap your two arrays in an iterable such as a tuple, like this: 为了解决这个问题,您需要将两个数组包装在一个可迭代的数组(例如元组)中,如下所示:

cc=np.concatenate((array_a,array_b))

This results in both arrays being passed as the first argument to the function. 这导致两个数组都作为第一个参数传递给函数。 (Edit: Wrapping in a list also works, ie concatenate([array_a,array_b]) . Haven't tried other forms). (编辑:包装在列表中也可以,例如concatenate([array_a,array_b]) 。尚未尝试其他形式)。

In your example, this will work, as the second argument defaults to 0 , which means the arrays can have a different length in the first dimension only (the zeroth-indexed dimension). 在您的示例中,这将起作用,因为第二个参数默认为0 ,这意味着数组只能在第一个维度(索引为零的维度)上具有不同的长度。 For you, these lengths are 10 and 40 , and the other dimension is 50 for both. 对于您来说,这些长度分别是1040 ,两者的另一个尺寸都是50 If your array dimensions were reversed, so they were now [50,10] and [50,40] , you would need to set the axis to the second dimension (index 1 ) like so: 如果将数组尺寸反转,则现在为[50,10][50,40] ,则需要将轴设置为第二维(索引1 ),如下所示:

cc=np.concatenate((array_a,array_b),1)

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

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