Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate two numpy arrays in the 4th dimension

Tags:

python

numpy

I have two numpy arrays with three dimensions (3 x 4 x 5) and I want to concatenate them so the result has four dimensions (3 x 4 x 5 x 2). In Matlab, this can be done with cat(4, a, b), but not in Numpy.

For example:

a = ones((3,4,5)) b = ones((3,4,5)) c = concatenate((a,b), axis=3) # error! 

To clarify, I wish c[:,:,:,0] and c[:,:,:,1] to correspond to the original two arrays.

like image 225
Marijn van Vliet Avatar asked Jan 17 '12 16:01

Marijn van Vliet


People also ask

How do you concatenate two arrays of different dimensions in Python?

You can either reshape it array_2. reshape(-1,1) , or add a new axis array_2[:,np. newaxis] to make it 2 dimensional before concatenation.

Can you concatenate NumPy arrays?

Joining Arrays Using Stack FunctionsWe can concatenate two 1-D arrays along the second axis which would result in putting them one over the other, ie. stacking. We pass a sequence of arrays that we want to join to the stack() method along with the axis.

How do you stack 3 NumPy arrays?

numpy. dstack stack the array along the third axis, so, if you stack 3 arrays ( a , b , c ) of shape (N,M) , you'll end up with an array of shape (N,M,3) . That gives you a (3,N,M) array. Pierre, many thanks for your answer, I will test this option in my project.

Can NumPy arrays be multidimensional?

In general numpy arrays can have more than one dimension. One way to create such array is to start with a 1-dimensional array and use the numpy reshape() function that rearranges elements of that array into a new shape.


2 Answers

Here you go:

import numpy as np a = np.ones((3,4,5)) b = np.ones((3,4,5)) c = np.concatenate((a[...,np.newaxis],b[...,np.newaxis]),axis=3) 
like image 125
JoshAdel Avatar answered Oct 04 '22 01:10

JoshAdel


What about

c = np.stack((a,b), axis=3) 
like image 26
Daniel Avatar answered Oct 04 '22 00:10

Daniel