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.

2
  • It works on DataFrames not lists. It probably also works on pandas series. Commented Jul 16, 2022 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]). Commented Jul 16, 2022 at 20:25

3 Answers 3

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]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.