-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]])
Ivan
  • 34,531
  • 8
  • 55
  • 100
  • 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]])`? – Ivan Aug 27 '21 at 09:38
  • I am looking for object as array([[[1, 2, 3], 7], [[4, 5, 6], 8]]) – user10397650 Aug 27 '21 at 09: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. – user10397650 Aug 27 '21 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. – hpaulj Aug 27 '21 at 15:27

1 Answers1

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)]
Captain Trojan
  • 2,800
  • 1
  • 11
  • 28
  • 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 Aug 27 '21 at 09:48
  • @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. – Captain Trojan Aug 27 '21 at 09:50
  • 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 Aug 27 '21 at 09:54
  • @user10397650 Oh I get it, wait a sec. – Captain Trojan Aug 27 '21 at 09:56