ehacinom
ehacinom

Reputation: 8894

Select a subset from 2D numpy array

From a 2D numpy array Z, I'd like to remove certain points, at indicies ix, iy.
ix, iy are currently sequential lists of the x-index and corresponding y-index, like so:

ix = range(10)
iy = range(10,20,1)

So I'd like Z[0][10], Z[1][11], etc. put into a new list or array.

What is the best (read: most pythonic) way of doing this? Perhaps there is a better way of finding these indicies so I get an array of [ix,iy], [ix+1,iy+1] etc.?

I have looked at this question. I don't know how to use the list comprehension syntax of the selected answer for 2 dimensions.

Upvotes: 3

Views: 3242

Answers (2)

roman
roman

Reputation: 117380

Can't test now, but AFAIK it could be done like Z[ix, iy] in numpy.
Also, you don't have to write range(10,20,1), you can use range(10,20)

Upvotes: 2

lynn
lynn

Reputation: 10794

[Z[y][x] for x, y in zip(ix, iy)]

(What zip(ix, iy) does is: make a list of tuples [(ix[0], iy[0]), (ix[1], iy[1]), ...], i.e. the x and y indices for each element we need.)

Upvotes: 0

Related Questions