user3550783
user3550783

Reputation: 21

Using Numpy Where on 2 2-d arrays

I am trying this code, but I am having a problem in this Numpy Where section:

import numpy as N
....
....
sfolat = N.ravel(N.where((lat>37.5689) & (lat<37.6689)))
sfolon = N.ravel(N.where((lon>-122.4250) & (lon<-122.3250)))
sfocoord = N.ravel(N.where((lat>37.5189) & (lat<37.7189)&(lon>-122.4750) & (lon<-122.2750)))

sfocoord returns

>>>sfocoord
array([204, 204, 205, 205, 145, 146, 145, 146])

Both lat and lon are dimensioned (428,614). I am trying to find locations at/around 37.6189,-122.3750 I would like input of what to change, so the code will work.

Upvotes: 0

Views: 142

Answers (1)

ilyas patanam
ilyas patanam

Reputation: 5324

numpy.where will return a length 2 tuple where the 2 elements are: an array of indices for the rows and an array of the corresponding indices for the columns that satisfied the condition.

numpy.ravel will flatten the tuple of the 2 arrays into a single array and you will no longer have 2 distinct arrays for the row and column indices.

To preserve the indices:

idx = numpy.where((lat>37.5689) & (lat<37.6689)&(lon>-122.4250) & (lon<-122.3250))

Based on your given output for sfocoord, your code will likely output,

>>>idx 
(array([204, 204, 205, 205]), array([145, 146, 145, 146]))

[204, 204, 205, 205] are the row indices and [145, 146, 145, 146] are the corresponding column indices were the conditions where satisfied.

To get the values from the lat array, using these indices, you can do:

lat[idx[0], idx[1]]

EDIT: A way for one to see the indices as row, column pairs:

>>>numpy.transpose(idx)
array([[204, 145],
   [204, 146],
   [205, 145],
   [205, 146]])

Upvotes: 1

Related Questions