【问题标题】:Is it possible to loop through operators (greater than/less than) in python?是否可以在python中循环遍历运算符(大于/小于)?
【发布时间】:2020-10-22 09:38:09
【问题描述】:

我希望能够遍历关系运算符。我有以下代码工作:

TP = df[(df.Truth == 1) & eval(df.age >= cutoff)]

我还有一些这样的行,其中真值和关系运算符不同,但其他一切都相同。 我尝试创建一个列表并使用 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)]

如何循环关系运算符而不是让 python 将其作为字符串而是作为实际运算符接收? 提前谢谢!!!

【问题讨论】:

    标签: python python-3.x pandas loops operators


    【解决方案1】:

    如果你想要实际的操作符,那么你应该使用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 的所有解决方案,在运行时评估字符串是一个潜在的安全问题。

    【讨论】:

    • 它有效,谢谢!我从来不知道这个算子函数。
    【解决方案2】:

    你可以试试

    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
    

    【讨论】:

    • 谢谢!我最终使用了运算符功能,但感谢您的帮助!
    【解决方案3】:

    您需要为eval() 提供一个字符串:

    truths = [[1,'>='],[0,'>='],[1,'<'],[0,'<']]
    for truth in truths:
         truth_val = truth[0]
         operator = truth[1]
         print(eval(f"{df.age}{operator}{cutoff}"))
    

    【讨论】:

    • 谢谢!我最终使用了运算符功能,但感谢您的帮助!
    猜你喜欢
    • 2018-05-27
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多