Cracking my head over the usage of tilde in Pandas

277 Views Asked by At

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.

3

There are 3 best solutions below

0
Digital Farmer On BEST ANSWER

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]
0
Vini On

The operator ~ does not work for a built-in Python list but does work for a Pandas DataFrame.

mask = [False, False, False, False, True, True, False]
df = pd.DataFrame(mask)

~df

#        0
# 0   True
# 1   True
# 2   True
# 3   True
# 4  False
# 5  False
# 6   True
0
Joshua Megnauth On

Operations on pandas' Series and DataFrames are vectorized via NumPy. You can read about NumPy's benefits over Python's standard data structures here.

For completion's sake, here is an example of bitwise NOT (~) with just an NDArray.

import numpy as np

mask = np.array([False, False, False, False, True, True, False])
inverted = ~mask

print(mask)
print(inverted)

Which prints:

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