英文:
Creating rule function using pandas dataframe;
问题
我有一个以这种格式的数据框;
rule_frame = pd.DataFrame({'PA_1' : ['A','B','A'],
'PA_2' : ['Low','Low','Low'],
'LA_1' : ['A','B','E'],
'LA_2' : ['Low','Low']})
我想创建一个函数,该函数以这个表格自动创建为输入。该函数基本上以每一行作为规则,如果符合规则,则返回true,否则返回false。
我所说的"自动创建函数"应该是这样的;
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
我之所以想要这样做的原因是列和行的大小可以不同。希望我能够解释清楚。
提前致谢。
英文:
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.
答案1
得分: 1
你可以尝试:
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)
# 这应该通过:
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
# 这不应该通过:
assert fn('A', 'High', 'E', 'High') == False
assert fn('A', 'High', 'B', 'High') == False
初始 df
:
PA_1 PA_2 LA_1 LA_2
0 A Low A Low
1 B Low B Low
2 A Low E High
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论