I have a dataframe in this format;
rule_frame = pd.DataFrame({'PA_1' : ['A','B','A'],
'PA_2' : ['Low','Low','Low'],
'LA_1' : ['A','B','E'],
'LA_2' : ['Low','Low']})
and I want to create a function that is automatically created by this table as an input. The function basically takes every single row as rules and return true, if not it should return false.
What i mean by "automatically created function" should be like;
def i_am_automatically_created(PA_1,PA_2,LA_1,LA_2):
if PA_1 == 'A' and PA_2 == 'Low' and LA_1 == 'A' and LA_2 == 'Low':
return True
elif PA_1 == 'B' and PA_2 == 'Low' and LA_1 == 'B' and LA_2 == 'Low':
return True
elif PA_1 == 'A' and PA_2 == 'Low' and LA_1 == 'E' and LA_2 == 'High':
return True
else:
return False
The reason why I want to do this flexible is that column and row sizes can differ. I hope I was able to explain.
Thanks in advance.
>Solution :
You can try:
def create_func(df):
all_funcs = []
for _, r in df.iterrows():
all_funcs.append(lambda *x, rules=r: all(r == v for v, r in zip(x, rules)))
return lambda *x: any(f(*x) for f in all_funcs)
fn = create_func(rule_frame)
# this should pass:
assert fn('A', 'Low', 'A', 'Low') == True
assert fn('B', 'Low', 'B', 'Low') == True
assert fn('A', 'Low', 'A', 'Low') == True
assert fn('A', 'Low', 'E', 'High') == True
# this shouldn't pass:
assert fn('A', 'High', 'E', 'High') == False
assert fn('A', 'High', 'B', 'High') == False
Initial df:
PA_1 PA_2 LA_1 LA_2
0 A Low A Low
1 B Low B Low
2 A Low E High