[英]why does ~True not work in pandas dataframe conditional
我正在尝试使用开关来打开和关闭熊猫数据框中的条件。 开关只是布尔变量,可以是 True 或 False。 问题是 ~True 不会像我预期的那样评估与 False 相同的值。 为什么这不起作用?
>>> dataframe = pd.DataFrame({'col1': [3, 4, 5, 6], 'col2': [6, 5, 4, 3]})
>>> dataframe
col1 col2
0 3 6
1 4 5
2 5 4
3 6 3
>>> dataframe.loc[dataframe.col1 <= dataframe.col2]
col1 col2
0 3 6
1 4 5
>>> dataframe.loc[(True) | (dataframe.col1 <= dataframe.col2)]
col1 col2
0 3 6
1 4 5
2 5 4
3 6 3
>>> dataframe.loc[(False) | (dataframe.col1 <= dataframe.col2)]
col1 col2
0 3 6
1 4 5
>>> dataframe.loc[(~True) | (dataframe.col1 <= dataframe.col2)]
col1 col2
0 3 6
1 4 5
2 5 4
3 6 3
>>> dataframe.loc[(~(True)) | (dataframe.col1 <= dataframe.col2)]
col1 col2
0 3 6
1 4 5
2 5 4
3 6 3
>>>
>>> dataframe = pd.DataFrame({'col1': [1, 2, 3, 4], 'col2': [True, False, False, True]})
>>> dataframe
col1 col2
0 1 True
1 2 False
2 3 False
3 4 True
>>> dataframe.loc[dataframe.col2]
col1 col2
0 1 True
3 4 True
>>> dataframe.loc[not dataframe.col2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/pandas/core/generic.py", line 1537, in __nonzero__
raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> dataframe.loc[dataframe.col2 == False]
col1 col2
1 2 False
2 3 False
这是一个 pandas 运算符行为(从 Numpy 实现)。
True
不是熊猫对象。 相反,它是一个布尔值。 很明显, ~
运算符并不意味着反转布尔值,仅在 Pandas 中。
如你看到的:
>>> ~True
-2
>>>
它给出-2
,这是常规的__invert__
魔术方法行为。
所以:
>>> bool(-2)
True
>>>
给出True
。
不要混淆 Pandas 和 Python 的行为,Pandas 在__invert__
用法上实现它,例如:
>>> ~pd.Series([True])
0 False
dtype: bool
>>>
如您所见,在 pandas(也是 Numpy)中,它反转了布尔值。 因此,如果你写:
>>> dataframe.loc[~pd.Series([True]).any() | (dataframe.col1 <= dataframe.col2)]
col1 col2
0 3 6
1 4 5
>>>
您可以清楚地看到它的行为等同于False
。
这里最好的方法是not
:
>>> dataframe.loc[(not True) | (dataframe.col1 <= dataframe.col2)]
col1 col2
0 3 6
1 4 5
>>>
我认为'~'不是你想要的,也许你想使用'not':
>>> dataframe.loc[(not True) | (dataframe.col1 <= dataframe.col2)]
col1 col2
0 3 6
1 4 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.