E. Wil
E. Wil

Reputation: 1

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)

    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"

What's the issue here, and how can I fix it? This error isn't very helpful...

Upvotes: 0

Views: 579

Answers (2)

Arthur Gordon-Wright
Arthur Gordon-Wright

Reputation: 31

The issue here is that np.concatenate expects an iterable sequence of array-like objects for the first argument. Here it just takes array_a as the first argument. It is taking array_b as the second argument, which specifies which array axis to concatenate along. 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. 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, i.e. concatenate([array_a,array_b]). Haven't tried other forms).

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). For you, these lengths are 10 and 40, and the other dimension is 50 for both. 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:

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

Upvotes: 1

Christian K.
Christian K.

Reputation: 2823

np.concatenate expects a tuple as argument, i.e. it should be

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.

Upvotes: 2

Related Questions