Combining 3 arrays in one 3D array in numpy

11,198

Solution 1

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])

Solution 2

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).

An alternative is to use directly:

np.array([a, b, c])

That gives you a (3,N,M) array.

What's the difference between the two? The memory layout. You'll access your first array a as

np.dstack([a,b,c])[...,0]

or

np.array([a,b,c])[0]
Share:
11,198
gerocampo
Author by

gerocampo

Updated on June 09, 2022

Comments

  • gerocampo
    gerocampo almost 2 years

    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?

  • gerocampo
    gerocampo over 11 years
    Pierre, many thanks for your answer, I will test this option in my project. Actually, it doesn't matter in my project if is (N,M,3) or (3,N,M).