clearseplex
clearseplex

Reputation: 719

Multidimensional slicing array Python

I want to "select" specific rows and columns of a 2D-np.array and don't know how to do this efficiently.

import numpy as np 

array = np.random.rand(4*100,4*360)

lon_min = np.array([-72.5, -72.5, -70, -67.5, -65, -62.5, -60, -57.5, -55, -52.5, -50])
lon_max = lon_min + 2.5
lat_min = np.array([-10, -7.5, -5, -4, -3, -3, -2, -1, -1, -1, -1])
lat_max = lat_min + 2.5 
indices_lon_min = (180+lon_min)*4
indices_lat_min = (50-lat_min)*4
indices_lon_max = indices_lon_min + 4*2.5
indices_lat_max = indices_lat_min -4*2.5
> indices_lat_min = [240. 230. 220. 216. 212. 212. 208. 204. 204. 204. 204.]
> indices_lat_max = [230. 220. 210. 206. 202. 202. 198. 194. 194. 194. 194.]
> indices_lon_min = [430. 430. 440. 450. 460. 470. 480. 490. 500. 510. 520.]
> indices_lon_max = [440. 440. 450. 460. 470. 480. 490. 500. 510. 520. 530.]

I hoped there is something like:

array[indices_lat_min.astype(int): indices_lat_max.astype(int), indices_lon_min.astype(int):indices_lon_max.astype(int)]

Basically I want to achieve

array[240:230, 430:440]

but with multiple "slices".

Upvotes: 3

Views: 87

Answers (1)

tenhjo
tenhjo

Reputation: 4537

Maybe something like this:

array[list(map(range, indices_lat_min.astype(int), indices_lat_max.astype(int))),
      list(map(range, indices_lon_min.astype(int), indices_lon_max.astype(int)))]

This is basically your idea, I just used map to get all the min max pairs in the index lists.

For a descending range:

array[list(map(range, indices_lat_min.astype(int), indices_lat_max.astype(int), np.full(indices_lat_max.size, -1))),
      list(map(range, indices_lon_min.astype(int), indices_lon_max.astype(int),))]

Upvotes: 1

Related Questions