Using numpy where to find the minimum of an array

1750 views python

I have two astropy tables, of different lengths::

print(type(a),  len(a))
print(type(b),  len(b))
<class 'astropy.table.table.Table'> 457
<class 'astropy.table.table.Table'> 355

I'm looking for the differences between the two tables, of which (obviously) will only be valid for the smaller number of the arrays::

delta = b - a 
print(type(delta),  len(delta))

I then what to find the values of 'a' and 'b' where the minimum is reached::

 a[np.where(delta = delta.min())]
 b[np.where(delta = delta.min())]

The latter works fine it seems, but for the former I get:

IndexError: boolean index did not match indexed array along dimension 0; dimension is 457 but corresponding boolean dimension is 355


answered question

@roganjosh: the smallest delta is not per se the smallest value for a and/or b. The smallest delta is typically where a is the largest relatively to b.

Shouldn't you be using the equality test, not the single '='?delta == delta.min()

1 Answer


We can create the list of deltas with:

n = min(len(a), len(b))
delta = b[:n] - a[:n]

then we can calculate the index where delta is minimum with:

idx = np.argmin(delta)

and then we can obtain the corresponding values with:

am, bm = a[idx], b[idx]

Note that if there are places where a is larger than b, then the delta will be negative, and this can count as the smallest value. If you want the "absolute value" of the difference, you should add np.abs(..):

delta = np.abs(b[:n] - a[:n])

posted this

Have an answer?


Please login first before posting an answer.