-1

I have two np.arrays x and y, and wish to find the minimum of the ratios x[i]/y[i] where y[i] is greater than 0, i.e for:

x = np.array([1,2,3,4,5])
y = np.array([-1,0,1,2,3])
minimumratio(x,y)

should return 5/3.

just using min(x/y) would yield -1, and possibly run into divide by 0 errors.

Achrbot
  • 1
  • 1
  • Right. Two issues with the posting: (1) You merely need to filter out the 0-divide case; (2) -1 *is* the minimum among the four defined ratios. What's the problem with that? – Prune Nov 26 '19 at 01:04
  • simply filtering out 0's from the y array would make the y - list shorter, and mismatch the index of the two arrays. I am trying to get a function which ignores any of the ratios where y less than 0. I thought about filtering y i.e: y = y[y>0] But then I would need to filter out the corresponding values in x as well (somehow). – Achrbot Nov 26 '19 at 01:09
  • You stream a new sequence of x/y if y != 0 – Prune Nov 26 '19 at 01:22

1 Answers1

0

I interpenetrate your task in the following way: Find the min of x/y with the condition that the result is still positive.

Therefore I would mask the array to get rid of all the cases we don't want to consider, such as one of the number is negative or the element of y is zero.

You could do that by setting those positions in the array to np.nan:

x = np.array([1,2,3,4,5], dtype=np.float)
y = np.array([-1,0,1,2,3], dtype=np.float)

y_cleared = np.copy(y)
y_cleared[y == 0] = np.nan # get rid of zeros
y_cleared[y < 0] = np.nan # get rid of negative values
y_cleared[x < 0] = np.nan # get rid of negative values
y_cleared
>>> array([nan, nan,  1.,  2.,  3.])

Then there are special numpy methodes to work with arrays and ignoring np.nan like:

np.nanmin(x/y_cleared)
>>> 1.6666666666666667
some_name.py
  • 777
  • 5
  • 16