Skip to content Skip to sidebar Skip to footer

Check If Values In One Column Is In Interval Values Of Another Column In Python

I have the following dataframe: import pandas as pd import numpy as np data = { 'index': [1, 2, 3, 4, 5], 'v1': [1100, 1776, 1228, 1640, np.NaN], 'v2': [1000, 1805, 123

Solution 1:

For v1 in [v2*0.95, v2*1.05] use:

df['res']=''foridx,valinenumerate(df.itertuples()):ifdf.loc[idx,'v1']>df.loc[idx,'v2']*0.95anddf.loc[idx,'v1']<df.loc[idx,'v2']*1.05:df.loc[idx,'res']='Yes'else:df.loc[idx,'res']='No'+---+-------+--------+--------+------+-----+||index|result|v1|v2|res|+---+-------+--------+--------+------+-----+|0|1|Y|1100.0|1000|No||1|2|Y|1776.0|1805|Yes||2|3|Y|1228.0|1231|Yes||3|4|N|1640.0|1425|No||4|5|N|NaN|1800|No|+---+-------+--------+--------+------+-----+

Solution 2:

Just using

(df.v1-df.v2).abs().le(100).map({True:'Yes',False:'No'})
Out[60]: 
0    Yes
1    Yes
2    Yes
3     No
4     No
dtype: object

Post a Comment for "Check If Values In One Column Is In Interval Values Of Another Column In Python"