Combining 3 arrays in one 3D array in numpy

2019-03-31 02:28发布

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条回答
再贱就再见
2楼-- · 2019-03-31 03:08

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])
查看更多
何必那么认真
3楼-- · 2019-03-31 03:16

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]
查看更多
登录 后发表回答