如何检查Pandas DataFrame中所有值是否严格为True?
Great question! The core issue here is that pd.DataFrame.all() and pd.DataFrame.any() rely on truthiness checks rather than strict equality to True. As you noticed, non-empty strings, lists, or non-zero numbers get evaluated as "truthy" even though they aren't actually the boolean value True, leading to incorrect results.
The == True approach works, but it's not the most Pythonic or precise (for example, 1 == True returns True in Python since booleans are subclasses of integers). Here are a couple of cleaner, more intentional ways to do this:
1. Use applymap with Identity Check (is True)
This method explicitly checks if every element is exactly the boolean object True, which avoids edge cases like numeric values or non-empty containers passing a truthiness check:
import pandas as pd df = pd.DataFrame([True, 'a']) strict_all_true = df.applymap(lambda x: x is True).all().all() # Returns False (correct)
applymap(lambda x: x is True)iterates over every element in the DataFrame and returns a boolean DataFrame where each cell isTrueonly if the original element is exactly the booleanTrue.- Calling
.all()twice: first to check all values in each column areTrue, then to check all column results areTrue(you can use.item()instead of the second.all()if you have a single-column DataFrame, like in your example).
2. Validate Data Type First (If Applicable)
If your DataFrame is supposed to contain only boolean values in the first place, you can combine a dtype check with the standard all() method for extra safety:
# First confirm all columns are boolean dtype if (df.dtypes == bool).all(): strict_all_true = df.all().all() else: strict_all_true = False # For df = pd.DataFrame([True, 'a']), this returns False (correct)
This ensures you're only checking boolean values, so you don't have to worry about non-boolean elements being misclassified as "truthy".
Why These Are More Pythonic
- They clearly express your intent: you want to check for the exact boolean value
True, not just any truthy value. - The identity check (
is True) is more precise than equality (== True) in Python, especially when dealing with numeric values that might accidentally equalTrue.
内容的提问来源于stack exchange,提问作者Elrond




