How can I return the column value where the index is greater than an integer and smaller than previouse index is smaller?

I have a small df like this:

Interval  Factor Prev_Interval                              
0.0002     1.0      0.0000
0.0005     1.5      0.0002
0.0010     2.0      0.0005
0.0050     2.5      0.0010
0.0150     3.0      0.0050
0.0500     3.5      0.0150
0.2500     4.0      0.0500
0.5000     4.2      0.2500
2.0000     4.3      0.5000

I need to find the ‘Factor’ where a float I calculated is < prev_interval and > Interval. So, if the float I calculates = 0.010, the output is 3.0 – i.e. between 0.0050 and 0.015.

Any ideas?

>Solution :

If the intervals are sorted and successive, the most efficient is to use numpy.searchsorted:

x = 0.010

out = df['Factor'].iloc[np.searchsorted(df['Interval'], x)]

A generic solution using boolean indexing:

out = df.loc[df['Interval'].gt(x) & df['Prev_Interval'].lt(x), 'Factor'].squeeze()

Output: 3.0

Leave a Reply