-1

I want to stack arrays with this code.

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([7, 8])
np.stack((a, b), axis=-1)

But it returns

ValueError: all input arrays must have the same shape error.

I expect the output to be:

array([[[1, 2, 3], 7],
       [[4, 5, 6], 8]])
4
  • 1
    Are you sure you want this np.object as a result, or are you looking for array([[[1, 2, 3, 7], [[4, 5, 6, 8]])? Commented Aug 27, 2021 at 9:38
  • I am looking for object as array([[[1, 2, 3], 7], [[4, 5, 6], 8]]) Commented Aug 27, 2021 at 9:42
  • @MichaelSzczesny it is not related with defining numpy array with different row size.I want to concatenate these arrays as shown in expected output. Commented Aug 27, 2021 at 10:19
  • Originally a is a (n,3) numeric array; in the combined array, it is broken up into n (3,) arrays. To recover a you'd have to use np.stack(res[:,0]). The combined array will use more memory, and for most operations will be harder to use. Commented Aug 27, 2021 at 15:27

1 Answer 1

0

I don't think that's a valid numpy array. You could probably do this by letting the array's dtype be an object (which could be anything, including a ragged sequence, such as yours).

data = [[[1, 2, 3], 7], [[4, 5, 6], 8]]

ar = np.array(data, dtype=object)

To build data, you can do:

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([7, 8])

data = [[_a, _b] for _a, _b in zip(a, b)]
Sign up to request clarification or add additional context in comments.

4 Comments

I see now output array cant write with ( ` ) import numpy as np arr = np.array([[[1, 2, 3], 7], [[4, 5, 6], 8]]) ( ` ) How to stack them on object without writing as ?
@user10397650 That's what the code I've posted does. If it does not do what you expected, please post what my code does for you and how does it differ from what you've expected.
I put code as example.There is 16000 rows to stack.I can't write them in data variable.I am looking for easy way to stack them in object automaticaly by numpy.
@user10397650 Oh I get it, wait a sec.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.