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}"))
添加回答
舉報