Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining 3 arrays in one 3D array in numpy

I have a very basic question regarding to arrays in numpy, but I cannot find a fast way to do it. I have three 2D arrays A,B,C with the same dimensions. I want to convert these in one 3D array (D) where each element is an array

D[column][row] = [A[column][row] B[column][row] c[column][row]] 

What is the best way to do it?

like image 483
gerocampo Avatar asked Sep 12 '12 19:09

gerocampo


People also ask

How do I combine 3D NumPy arrays?

One way is to use np. dstack which concatenates the arrays along the third axis (d is for depth). You could also use np. concatenate((a, a), axis=2) .

How do you merge 3D arrays in Python?

In Python you can use : '+' to combine two lists into a new list. you can use the extend() method to extend a list in place (ie add one list to the end of another).

How do I combine multiple NumPy arrays?

Use numpy. concatenate() to merge the content of two or multiple arrays into a single array. This function takes several arguments along with the NumPy arrays to concatenate and returns a Numpy array ndarray. Note that this method also takes axis as another argument, when not specified it defaults to 0.

How do you make a 3D NumPy array in Python?

Use numpy. array() to create a 3D NumPy array with specific values. Call numpy. array(object) with object as a list containing x nested lists, y nested lists inside each of the x nested lists, and z values inside each of the y nested lists to create a x -by- y -by- z 3D NumPy array.


1 Answers

You can use numpy.dstack:

>>> import numpy as np
>>> a = np.random.random((11, 13))
>>> b = np.random.random((11, 13))
>>> c = np.random.random((11, 13))
>>> 
>>> d = np.dstack([a,b,c])
>>> 
>>> d.shape
(11, 13, 3)
>>> 
>>> a[1,5], b[1,5], c[1,5]
(0.92522736614222956, 0.64294050918477097, 0.28230222357027068)
>>> d[1,5]
array([ 0.92522737,  0.64294051,  0.28230222])
like image 122
DSM Avatar answered Sep 23 '22 20:09

DSM