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?
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])
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.