Issue
I have multiple arrays of equal size, and I want to concatenate the values in each cell to produce an output array of the same size, but where each element is a list. How can I do this?
Example.
Input:
a = [[1,2],
[3,4]]
b = [[5,6],
[7,8]]
Desired output:
c = [[[1,5],[2,6]],
[[3,7],[4,8]]]
How can I achieve this? My arrays are actually NumPy arrays, if that helps.
Followup Question: Concatenate Iteratively
The first answer suggests using np.dstack, which works for the above example.
How do I do the concatenation in an iterative fashion? After obtaining
c = [[[1,5],[2,6]],
[[3,7],[4,8]]]
if I have
d = [[9,10],
[11,12]]
I want to "concatenate" c and d to obtain
e = [[[1,5,9],[2,6,10]],
[[3,7,11],[4,8,12]]]
Solution
You can use np.dstack
.
>>> a
array([[1, 2],
[3, 4]])
>>> b
array([[5, 6],
[7, 8]])
>>> np.dstack((a,b))
array([[[1, 5],
[2, 6]],
[[3, 7],
[4, 8]]])
See help(np.dstack)
for more information and examples
>>> help(np.dstack)
Help on function dstack in module numpy:
dstack(tup)
Stack arrays in sequence depth wise (along third axis).
This is equivalent to concatenation along the third axis after 2-D arrays
of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape
`(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by
`dsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate`, `stack` and
`block` provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of arrays
The arrays must have the same shape along all but the third axis.
1-D or 2-D arrays must have the same shape.
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays, will be at least 3-D.
Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
Answered By - Abdul Niyas P M
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.