【发布时间】:2021-06-26 17:46:55
【问题描述】:
我发现自己正在尝试分析数据集并找出一些变量之间的相关性。
我需要添加一个循环,为 if 语句添加一个逻辑测试:
编辑: 例子: 以这个数据框为例
In [11]: df
Out[11]:
INPUT1 INPUT2 INPUT3 ... OUTPUT
0 8 5 6 ... 1
1 3 2 5 ... 0
2 3 1 5 ... 1
3 1 2 5 ... 0
4 4 3 5 ... 0
我正在测试输入组合以检查它们与输出的匹配程度
def greater_than(a,b):
return a > b
def greater_equal_than(a,b):
return a >= b
def lower_equal_than(a,b):
return a <= b
def lower_than(a,b):
return a < b
def equal(a,b):
return a == b
operation = { '>': greater_than, '>=': greater_equal_than, '<=': lower_equal_than, '<': lower_than }
escenario = pd.DataFrame(columns=['esc','pf'])
for i in range(len(names)):
for j in names[i+1:]:
for op in operation:
escenario['esc'] = df.apply(lambda x : 1 if operation[op]( names[i], j ) else 0, axis=1)
escenario['pf'] = df['OUTPUT']
match = escenario.apply(lambda x : 1 if x['pf'] == 1 and x['pf'] == x['esc'] else 0, axis=1 )
percent_match = (100 * match.sum())/escenario['pf'].sum()
percent_no_match = (100 *(escenario['esc'].sum() - match.sum())) / escenario['esc'].sum()
print( f"{names[i]} {op} {j} -> { percent_match } / {percent_no_match} " )
我需要检查使 percent_match 接近 100% 和 percent_no_match 接近 0% 的所有输入组合组合
例如:
first iteration:
INPUT2 < INPUT3
SECOND INTERATION
INPUT2 < INPUT3 and INPUT1 > INPUT2
现在我正在运行代码,对打印进行排序并获取匹配接近 100 的一对,并修改代码以添加匹配,示例:
First run better output is INPUT2 < INPUT3
然后我修改这一行:
escenario['esc'] = df.apply(lambda x : 1 if operation[op]( names[i], j ) else 0, axis=1)
添加第一个输出,例如:
escenario['esc'] = df.apply(lambda x : 1 if df['INPUT2'] < DF['INPUT3'] and operation[op]( names[i], j ) else 0, axis=1)
然后再次检查... 最后一部分是我想通过循环自动化的部分。 谢谢
【问题讨论】:
-
此时,一个对你的任务一无所知的人,真的还是一无所知。为了让人们开始理解,我们需要查看与示例输出匹配的示例输入以及您已经尝试过的内容
标签: python-3.x loops