hop*_*288 3 python loops operators python-3.x pandas
我希望能够遍历关系运算符。我有以下代码工作:
TP = df[(df.Truth == 1) & eval(df.age >= cutoff)]
Run Code Online (Sandbox Code Playgroud)
我还有几行,其中真值和关系运算符不同,但其他一切都相同。我尝试创建一个列表并使用 eval 函数,但我知道这是错误的,因为我什至无法克服语法错误。
truths = [[1,'>='],[0,'>='],[1,'<'],[0,'<']]
for truth in truths:
truth_val = truth[0]
operator = truth[1]
TP = df[(df.Truth == truth) & eval(df.age operator cutoff)]
Run Code Online (Sandbox Code Playgroud)
如何循环关系运算符而不是让 python 将其作为字符串而是作为实际运算符?先感谢您!!!
如果您想要实际的运算符,那么您应该使用该operator库:
import operator as op
Run Code Online (Sandbox Code Playgroud)
那么你的代码应该是这样的:
truths = [[1, op.ge], [0, op.ge], [1, op.lt], [0, op.lt]]
for truth in truths:
truth_val = truth[0]
operator = truth[1]
TP = df[(df.Truth == truth) & operator(df.age, cutoff)]
Run Code Online (Sandbox Code Playgroud)
这是最安全的解决方案,所有基于的解决方案eval都非常不鼓励,在运行时评估字符串是一个潜在的安全问题。
| 归档时间: |
|
| 查看次数: |
139 次 |
| 最近记录: |