3

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".

4
  • Your array has size (400, 360) but you want to access it at larger values ie. 530 Commented Jan 16, 2020 at 9:19
  • @scleronomic (400, 4*360) Commented Jan 16, 2020 at 9:22
  • Hoops sorry. But still valid, index_lat_max goes to 406 Commented Jan 16, 2020 at 9:25
  • @scleronomic You are right, I have to check this. Commented Jan 16, 2020 at 9:26

1 Answer 1

1

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),))]
Sign up to request clarification or add additional context in comments.

2 Comments

It worked, but I had to change my array so that the range for lat is now descending. Is there a way to modify this?
One could add the argument: np.repeat(-1, indices_lat_max.size) to the map function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.