I am trying to sum the inverse of a bool pd.Series. pd.Series.sum() works fine until i use the ~ operator. At which point .sum() starts throwing negative values.
Here is a very simple example:
.sum() works fine:
import pandas as pd
>>> pd.Series([True]).sum()
1
>>> pd.Series([False]).sum()
0
But when I invoke the ~ operator, things break:
>>> ~pd.Series([False]).sum()
-1
>>> ~pd.Series([True]).sum()
-2
Notably nothing seems wrong with the data:
>>> ~pd.Series([True])
0 False
dtype: bool
>>> ~pd.Series([False])
0 True
dtype: bool
What is going on here? How can I use sum on the inverse of a pd.Series object?
>Solution :
You want to apply ~ to the Series, not the result of the Series‘s sum method. To do that, you need parentheses, because attribute access has higher precedence than any operator.
>>> pd.Series([True]).sum()
1
>>> (~pd.Series([True])).sum()
0