[英]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.