0

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.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
DDogu
  • 5
  • 4
  • It works on `DataFrame`s not lists. It probably also works on pandas series. – NelsonGon Jul 16 '22 at 20:24
  • 1
    `~` is not defined for a Python `list`. You have to turn a list into a NumPy array or a Pandas series or DataFrame to be able to use `~`. For example, `~np.array(mask)` returns `array([ True, True, True, True, False, False, True])`. – sj95126 Jul 16 '22 at 20:25

3 Answers3

4

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]
Digital Farmer
  • 1,705
  • 5
  • 17
  • 67
1

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
Vini
  • 875
  • 1
  • 7
  • 14
0

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]
Joshua Megnauth
  • 281
  • 1
  • 7