[Numpy-discussion] Getting 3-D array values from a 2-D array of indexes
Robert Kern
robert.kern at gmail.com
Wed Jan 10 00:48:16 EST 2007
Jordan Dawe wrote:
> I have a 3D array A of shape (nz, ny, nx) and a 2D array B of shape (ny,
> nx) that contains integer indexes. I want to generate a 2D array C of
> shape (ny, nx) composed of the values of A at the z-indexes specified in
> B. Is there an easy way to do this?
An alternative to Pau's suggestion is to use the .choose() method, which is
tailor-made for this use-case.
In [9]: nz, ny, nx = (3, 4, 5)
In [10]: B = array([[0, 1, 2, 1, 0], [1, 2, 1, 0, 1], [2, 1, 0, 1, 2], [1, 0, 1,
2, 1]])
In [11]: B
Out[11]:
array([[0, 1, 2, 1, 0],
[1, 2, 1, 0, 1],
[2, 1, 0, 1, 2],
[1, 0, 1, 2, 1]])
In [12]: A = arange(nz*ny*nx).reshape((nz,ny,nx))
In [13]: A
Out[13]:
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39]],
[[40, 41, 42, 43, 44],
[45, 46, 47, 48, 49],
[50, 51, 52, 53, 54],
[55, 56, 57, 58, 59]]])
In [14]: B.choose(A)
Out[14]:
array([[ 0, 21, 42, 23, 4],
[25, 46, 27, 8, 29],
[50, 31, 12, 33, 54],
[35, 16, 37, 58, 39]])
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the NumPy-Discussion
mailing list