【问题标题】:Alternative to the pandas negation operatorpandas 否定运算符的替代方案
【发布时间】:2019-01-14 22:59:07
【问题描述】:

我正在尝试在我的 jinja2 模板之一中使用 pandas 否定运算符 ~,但我认为它与他们的 special operator ~ 冲突。

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

产生以下异常...

jinja2.exceptions.TemplateSyntaxError, unexpected '~'

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

【问题讨论】:

  • 试试df['is_test_result_pass'].__neg__()

标签: python pandas jinja2


【解决方案1】:

使用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】:

    看起来比~ 操作符更卡了,我也不能使用列切片操作符:,它会在模板编译时产生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() %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 2013-02-10
      • 2017-05-04
      • 1970-01-01
      相关资源
      最近更新 更多