3

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?

4
  • The dimensions of an n-d array must be expressible as a tuple (d1, d2, ..., dn). How do you propose your scheme to be able to do that? Commented Jul 22, 2020 at 4:27
  • you're getting the error because you can't do that with numpy arrays. Any given dimension must always be the same length throughout the array. Commented Jul 22, 2020 at 4:28
  • Perhaps you can set the empty values to -1 or NaN instead. Commented Jul 22, 2020 at 4:28
  • That's a list of lists, not a 3d array! Commented Jul 22, 2020 at 4:34

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

This answer does not help OP to get what they are looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.