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

Convert pandas series to boolean doesn't work

I have a data frame df and column col. The value of the last entry is NaN, like this

df['col'][-1:]

48   NaN
Name: col, dtype: float64

I’m trying to apply a condition on that last value, but running this gives a ValueError:

if dcc_td['da_4'][-1:].isna():
    print('Missing value.')

I did some search and it seems converting the series to boolean value may help. But running both of these conditions gives the same result:

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

if df['col'][-1:].isna().bool():
    print('Missing value.')

Missing value.

And:

if ~df['col'][-1:].isna().bool():
    print('Missing value.')

Missing value.

Further, if I run this I get True:

df['col'][-1:].isna().bool()

But if I run this I get -2, which I expected to see False:

~df['col'][-1:].isna().bool()

What did I misunderstand about these concepts?

EDIT: A simple solution for the ValueError issue is:

if df['col'][-1:].isna().all():
    print('Missing value.')

But still, the boolean issue is quite helpful to understand.

>Solution :

~ is bitwise operator, when you do ~True you are actually doing ~1 which will invert the each bit from binary representation of 1. [1]

What you want is logical operator not.

[1] Why does bitwise "not 1" equal -2?

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