3 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個贊
如果你想要實(shí)際的操作員,那么你應(yīng)該使用operator庫:
import operator as op
那么你的代碼應(yīng)該是這樣的:
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這是最安全的解決方案,強(qiáng)烈不鼓勵所有基于的解決方案,在運(yùn)行時評估字符串是一個潛在的安全問題。

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超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貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超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}"))
添加回答
舉報