As mentioned, there are some issues with the conditions, as only two of the values met the conditions. I add a Condition Met?
column for you to visualize this, and from there you can drop that column or only keep True
rows.
In the data below df
is your first dataframe in your question and df2
is the second:
df2 = pd.merge(df,df1,how='left',on='Variable')
df2['Condition Met?'] = df2['Value'].between(df2['from'], df2['to'])
df2 = df2.sort_values(['Variable', 'Value', 'Condition Met?']).drop_duplicates(['Variable', 'Value'], keep='last')
# df2 = df2[df2['Condition Met?']].drop('Condition Met?', axis=1)
df2
Out[1]:
Variable Value Classif from to Condition Met?
0 Variable_1 18 A 17 24 True
11 Variable_1 37 C 31 35 False
8 Variable_1 54 C 31 35 False
5 Variable_1 65 C 31 35 False
16 Variable_2 22 B 20 25 True
14 Variable_2 37 C 26 50 True
23 Variable_2 66 C 26 50 False
20 Variable_2 78 C 26 50 False
After dropping Condtion Met? rows that are False
as well as the column itself:
df2 = pd.merge(df,df1,how='left',on='Variable')
df2['Condition Met?'] = df2['Value'].between(df2['from'], df2['to'])
df2 = df2.sort_values(['Variable', 'Value', 'Condition Met?']).drop_duplicates(['Variable', 'Value'], keep='last')
df2 = df2[df2['Condition Met?']].drop('Condition Met?', axis=1)
df2
Out[2]:
Variable Value Classif from to
0 Variable_1 18 A 17 24
16 Variable_2 22 B 20 25
14 Variable_2 37 C 26 50
Alternatively, you can return NaN
in the Classif
column if condition is not met.
df2 = pd.merge(df,df1,how='left',on='Variable')
df2['Condition Met?'] = df2['Value'].between(df2['from'], df2['to'])
df2 = df2.sort_values(['Variable', 'Value', 'Condition Met?']).drop_duplicates(['Variable', 'Value'], keep='last')
df2['Classif'] = df2['Classif'].where(df2['Condition Met?'],np.nan)
df2 = df2.drop('Condition Met?', axis=1)
df2
Out[3]:
Variable Value Classif from to
0 Variable_1 18 A 17 24
11 Variable_1 37 NaN 31 35
8 Variable_1 54 NaN 31 35
5 Variable_1 65 NaN 31 35
16 Variable_2 22 B 20 25
14 Variable_2 37 C 26 50
23 Variable_2 66 NaN 26 50
20 Variable_2 78 NaN 26 50