0

I'm new to python and I have found tons of my questions have already been answered. In 7 years of coding various languages, I've never actually posted a question on here before, so I'm really stumped this time.

I'm using python 3.6

I have a pandas dataframe with a column that is just Boolean values. I have some code that I only want to execute if all of the rows in this column are True.

Elsewhere in my code I have used:

if True not in df.column:

to identify if not even a single row in df is True. This works fine.

But for some reason the converse does not work:

if False not in df.column:

to identify if all rows in df are True.

Even this returns False:

import pandas as pd

S = pd.Series([True, True, True])

print(False not in S)

But I have found that adding .values to the series works both ways:

import pandas as pd

S = pd.Series([True, True, True])

print(False not in S.values)

The other alternative I can think of is to loop through the column and use the OR operator to compare each row with a variable initialized as True. Then if the variable makes it all the way to the end as True, all must be true.

SO my question is: why does this return False?

import pandas as pd

S = pd.Series([True, True, True])

print(False not in S)
WHeward
  • 3
  • 1
  • 3
  • I believe DYZ provides the answer to your question, and GabrielA provides a solution for what you are trying to achieve. – Alexander Jan 21 '18 at 07:42

3 Answers3

2

It's not directly what you're asking but you can use .all() on a boolean series to determine if all values are true. Something like:

if df["column_name"].all():
    #do something
Gabriel A
  • 1,779
  • 9
  • 12
1

False not in S is equivalent to False not in S.index. Since the first index element is 0 (which, in turn, is numerically equivalent to False), False is technically in S.

DYZ
  • 55,249
  • 10
  • 64
  • 93
1

When you call s.values you are going to have access to a numpy.array version of the pandas Series/Dataframe.

Pandas provides a method called isin that is going to behave correctly, when calling s.isin([False])

rickyalbert
  • 2,552
  • 4
  • 21
  • 31