5

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?

2 Answers 2

15

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])
Sign up to request clarification or add additional context in comments.

Comments

7

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]

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.