Skip to content

Index 3D array with index of last axis stored in 2D array #3949

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
zxdawn opened this issue Apr 7, 2020 · 2 comments
Closed

Index 3D array with index of last axis stored in 2D array #3949

zxdawn opened this issue Apr 7, 2020 · 2 comments

Comments

@zxdawn
Copy link

zxdawn commented Apr 7, 2020

This is copied from a question on stackoverflow.

I have a ndarray of shape(z,y,x) containing values. I am trying to index this array with another ndarray of shape(y,x) that contains the z-index of the value I am interested in.
How do I have to index val_arr with z_indices to get the values at the desired z-axis position?

MCVE Code Sample

import numpy as np
val_arr = np.arange(27).reshape(3, 3, 3)

z_indices = np.array([[1, 0, 2],
                      [0, 0, 1],
                      [2, 0, 1]])

index_array = z_indices.choose(val_arr)
print(index_array)

xarray version

import numpy as np
import xarray as xr

val_arr = xr.DataArray(np.arange(27).reshape(3, 3, 3),
                       dims=['z', 'y', 'x'])

z_indices = xr.DataArray(np.array([[1, 0, 2],
                      [0, 0, 1],
                      [2, 0, 1]]),
                      dims=['y', 'x'])

index_array = np.choose(z_indices, val_arr)
print(index_array)

Expected Output

<xarray.DataArray (y: 3, x: 3)>
array([[ 9,  1, 20],
       [ 3,  4, 14],
       [24,  7, 17]])
Dimensions without coordinates: y, x

Problem Description

Is this feature of choose supported in xarray?

@johnomotani
Copy link
Contributor

I think indexed_array = val_arr.isel(z=z_indices) should work, if I'm understanding what you want. I haven't tested though...

@zxdawn
Copy link
Author

zxdawn commented Apr 7, 2020

@johnomotani Thanks, it works. Sorry for this simple question ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants