代码之家  ›  专栏  ›  技术社区  ›  jxramos

熊猫否定运算符的替代项

  •  2
  • jxramos  · 技术社区  · 8 年前

    我想用熊猫否定运算符 ~ 在我的一个 jinja2 但我相信这与他们的 special operator ~ .

    {% for row in df.loc[ ~(df['is_test_result_pass']) , : ].itertuples() %}
    

    产生以下异常。。。

    jinja2.exceptions.TemplateSyntaxError, unexpected '~'
    

    我可以在python端执行该操作,并传递另一个带有否定选择的变量,但是~操作符映射到的方法名等价于什么,我可以在模板中调用它。

    2 回复  |  直到 8 年前
        1
  •  2
  •   jezrael    8 年前

    使用 numpy.logical_not :

    df = pd.DataFrame({'is_test_result_pass':[True, False, False, True]})
    
    print (df['is_test_result_pass'])
    0     True
    1    False
    2    False
    3     True
    Name: is_test_result_pass, dtype: bool
    
    print (np.logical_not(df['is_test_result_pass']))
    0    False
    1     True
    2     True
    3    False
    Name: is_test_result_pass, dtype: bool
    
        2
  •  0
  •   jxramos    8 年前

    看起来甚至比 ~ 操作员窒息了,我也不能使用列切片运算符 : ,它将产生 SyntaxError: invalid syntax 当模板编译时

    然而,以下两种方法都使用@piRSquared的提示进行了相同的工作。。。。

    {% for row in df.loc[ df['is_test_result_pass'].eq(False) ].itertuples() %}
    {% for row in df.loc[ df['is_test_result_pass'].__neg__() ].itertuples() %}