3 回答
TA贡献1856条经验 获得超17个赞
如果你想要实际的操作员,那么你应该使用operator库:
import operator as op
那么你的代码应该是这样的:
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)]
eval这是最安全的解决方案,强烈不鼓励所有基于的解决方案,在运行时评估字符串是一个潜在的安全问题。
TA贡献1815条经验 获得超10个赞
你能试一下吗
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)] # notice cutoff here should be string
TA贡献1111条经验 获得超0个赞
您需要提供eval()一个字符串:
truths = [[1,'>='],[0,'>='],[1,'<'],[0,'<']]
for truth in truths:
truth_val = truth[0]
operator = truth[1]
print(eval(f"{df.age}{operator}{cutoff}"))
添加回答
举报