Combine 2D arrays with different shape into a 3D array numpy

Viewed 1112

I'm trying to combine 2 2D arrays with different size into a 3D array like this:

a1 = np.array([[0,0,0,0,0,0],[1,1,1,1,1,1]])
print(a1.shape) #(2,6)

a2 = np.array([[0,0,0,0],[1,1,1,1]])
print(a2.shape) #(2,4)

combined = np.stack((a1,a2)) #ValueError: all input arrays must have the same shape 

I'm trying to get the following:

>>> [[[0,0,0,0,0,0],[1,1,1,1,1,1]],[[0,0,0,0],[1,1,1,1]]]

Could someone help me?

2 Answers

You cannot have a non-rectangular shape arrays in numpy. Now you have some options depending on what you are trying to achieve:

  1. Use lists:

    combined = [a1.tolist(), a2.tolist()]
    #[[[[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1]]], [[[0, 0, 0, 0], [1, 1, 1, 1]]]]
    
  2. Use a list of arrays:

    combined = [a1, a2]
    #[array([[[0, 0, 0, 0, 0, 0],[1, 1, 1, 1, 1, 1]]]), array([[[0, 0, 0, 0],[1, 1, 1, 1]]])]
    
  3. Use an array of lists:

    combined = np.array([a1.tolist(), a2.tolist()])
    #[[[list([0, 0, 0, 0, 0, 0]) list([1, 1, 1, 1, 1, 1])]], [[list([0, 0, 0, 0]) list([1, 1, 1, 1])]]]
    

I would suggest using lists, since there is not much benefit of using numpy when elements are objects like lists.

As the numpy docs tell, the arrays must be of the same shape. Try this:-

a1 = np.array([[0,0,0,0,0,0],[1,1,1,1,1,1]])
print(a1.shape) #(2,6)

# notice extra 2's and 3's to make it of same shape as a1
a2 = np.array([[0,0,0,0,2,2],[1,1,1,1,3,3]]) 
print(a2.shape) #(2,4)

combined = np.stack((a1,a2))

To get this :-

[[[0,0,0,0,0,0],[1,1,1,1,1,1]],[[0,0,0,0],[1,1,1,1]]]

you can try python lists. And if you want to stick to numpy arrays try padding the a2 array with 0 or something, otherwise shape mismatch of a1 and a2 won't stack them along the third dimension.

Which final array should it make:- 2x4x2 (as per a2 shape) or 2x6x2 (as per a1 shape)? Since both have different shapes.

Related