nath
nath

Reputation: 113

Filter all rows in a pandas DataFrame where a given value is between two column values

i already have this dataframe that contains two columns with floating number,i want to extract a dataframe based on this value 10.9 which is not on the dataframe, so that it will return the dataframe in the ranges of 10.9, look the table below

   Words    Start_time(in sec)  End_time(in secs)   Time_per_words
0   let         0.1                 2.5                2.6
1   me          2.5                 2.6                5.1
2   tell        2.6                 2.9                5.5
3   you         2.9                 3.0                5.9
4   about       3.0                 3.2                6.2
5    4          10.7                11.0               21.7

Expected Result: when i filter with the 3.10, i want to get this dataframe below, Thank you in advance

   Words    Start_time(in sec)  End_time(in secs)   Time_per_words
4   4           10.7                11.0               21.7

Upvotes: 1

Views: 598

Answers (1)

cs95
cs95

Reputation: 402523

Build an IntervalIndex if you intend to do this operation often:

val = 3.1
idx = pd.IntervalIndex.from_arrays(
    df['Start_time(in sec)'], df['End_time(in secs)'])

idx.contains(val)
#  array([False, False, False, False,  True])

df[idx.contains(val)]  

   Words  Start_time(in sec)  End_time(in secs)  Time_per_words
4  about                 3.0                3.2             6.2

Otherwise, this one-off boolean indexing op will suffice:

df[(df['Start_time(in sec)'] <= val) & (val <= df['End_time(in secs)'])]

   Words  Start_time(in sec)  End_time(in secs)  Time_per_words
4  about                 3.0                3.2             6.2

Upvotes: 8

Related Questions