替代熊猫否定运算符

时间:2018-08-07 19:06:39

标签: pandas jinja2

我正在尝试在我的~模板之一中使用熊猫求反运算符jinja2,但我认为它与special operator ~冲突。

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

产生以下异常...

jinja2.exceptions.TemplateSyntaxError, unexpected '~'

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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