简体   繁体   中英

If a value is between an interval, select the value on the same row in another column

My dataframe looks like this:

        s     gamma_star    
0   0.000000    0.6261
1   0.000523    0.6262  
2   0.000722    0.6263  
3   0.000861    0.6267  
4   0.000972    0.6269  
5   0.001061    0.6260  
6   0.001147    0.6263  
7   0.001218    0.6261  

I have a value s = 0.000871 , what I need to look for is the related gamma_star that belongs to this s . In the example above it would be s is between 3 0.000861 0.6261 and 4 0.000972 0.6261 then it's related gamma_star is 0.6267 ! I am a bit stuck and do not know how to sart, any idea? Thanks!

You could do:

df.loc[(df.s > s).idxmax()-1, 'gamma_star']
# 0.6267

Where the use condition will be indicating the starting point on which the condition is satisfied

(df.s > s)

0    False
1    False
2    False
3    False
4     True
5     True
6     True
7     True
Name: s, dtype: bool

and by taking the idxmax() we can find the beginning of the interval:

(df.s > s).idxmax()-1
# 3

You could do it with a loop, if you go through the s-values.

for i in range(len(s)-1):
    if given_value > s[i] and given_value < s[i+1]:
        gamma_s_wanted = gamma_star[i]
        break
    else:
        gamma_s_wanted = gamma_star[-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM