Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading