Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Good afternoon

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?

Many thanks for your help,

German

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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])
share|improve this answer
    
Many thanks, this is what I want!!! –  gerocampo Sep 12 '12 at 21:33

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|improve this answer
    
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). –  gerocampo Sep 13 '12 at 12:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.