Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling pd.Series.sum() breaks when using `~` operator

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading