pythonpandaslistnegation

Cracking my head over the usage of tilde in Pandas


I read numerous similar posts about the subject here but still cannot make anything out of this.

I have this simple list:

mask =[False, False, False, False, True, True, False]

And am attempting to negate this list via the ~ operator (this is the exercise I have been given). Though:

neg_mask = ~mask

gives me the following error:

TypeError                                 Traceback (most recent call last)
<ipython-input-111-b1d572533400> in <module>
----> 1 neg_mask =~mask

TypeError: bad operand type for unary ~: 'list'

Tried on python and ipython 3. Well, according to the instructions this is supposed to work.


Solution

  • To work with the ~ operator you first need to generate a DataFrame like for example:

    import pandas as pd
    
    mask = [False, False, False, False, True, True, False]
    mask = pd.DataFrame(mask, columns=['mask'])
    mask = ~mask
    print(mask)
    

    Output:

        mask
    0   True
    1   True
    2   True
    3   True
    4  False
    5  False
    6   True
    

    If you want directly via the list, do a list comprehension working with not:

    mask = [False, False, False, False, True, True, False]
    mask = [not i for i in mask]
    print(mask)
    

    Output:

    [True, True, True, True, False, False, True]