c = np.array([[2,2],[2]])
d = np.array([[3,3],[3]])
res=np.concatenate((c,d),axis=1)
I tried concatenating c and d using np.concatenate but it gives me an error due to variable dimensions.
numpy.AxisError: axis 1 is out of bounds for array of dimension 1
I want to concatenate c and d to give :
res=np.array([[2,3],[2,3]],[[2,3]])
How can I get this result using numpy library functions? Thanks in Advance :)
CodePudding user response:
Code:
[np.dstack((res[i], res[i 2]))[0] for i in range(len(np.concatenate((c,d))[:2]))]
Output:
[array([[2, 3],
[2, 3]]),
array([[2, 3]])]
CodePudding user response:
Did you get the warning when you created the arrays? Did you look at the arrays?
In [183]: c = np.array([[2,2],[2]])
...: d = np.array([[3,3],[3]])
C:\Users\paul\AppData\Local\Temp\ipykernel_6304\2700245180.py:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
c = np.array([[2,2],[2]])
C:\Users\paul\AppData\Local\Temp\ipykernel_6304\2700245180.py:2: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
d = np.array([[3,3],[3]])
In [184]: c
Out[184]: array([list([2, 2]), list([2])], dtype=object)
In [185]: c.shape
Out[185]: (2,)
That is 1d, so of course np.concatenate
will complain if you specify axis 1! It can only use axis 0
In [186]: np.concatenate((c,d))
Out[186]: array([list([2, 2]), list([2]), list([3, 3]), list([3])], dtype=object)
making a (4,) shape array.
stack
is a variant that can join arrays on a new axis:
In [188]: np.stack((c,d))
Out[188]:
array([[list([2, 2]), list([2])],
[list([3, 3]), list([3])]], dtype=object)
In [189]: np.stack((c,d),axis=1)
Out[189]:
array([[list([2, 2]), list([3, 3])],
[list([2]), list([3])]], dtype=object)
Look at your desired result
In [191]: res=np.array(([[2,3],[2,3]],[[2,3]]),object)
In [192]: res
Out[192]: array([list([[2, 3], [2, 3]]), list([[2, 3]])], dtype=object)
(this too is (2,) shape; note it handles the 1 element lists different from the 2 element ones).
Compare that to what we get with a plain list "transpose":
In [193]: list(zip(c,d))
Out[193]: [([2, 2], [3, 3]), ([2], [3])]
Wrapped in np.array
, that makes a (2,2) object dtype.
Redefining c
to contain a list and a number:
c1 = np.array([[2,2],2],object)
In [212]: np.stack((c1,d1),axis=1)
Out[212]:
array([[list([2, 2]), list([3, 3])],
[2, 3]], dtype=object)