Pandas中对两列应用lambda函数判断非全NaN时遇ValueError
The error you're encountering stems from how your lambda function interacts with row-level Series data. When using apply() on a DataFrame, each x passed to the lambda is a Series representing an entire row. Calling pd.isna(x) returns a boolean Series (one value per column), not a single boolean—and Pandas can't evaluate the "truth value" of a Series directly in an if statement, hence the ambiguous truth value error.
Here are two clean, efficient ways to solve your problem:
Method 1: Use notna() + any(axis=1)
This approach checks if any value in the row is not NaN (which aligns exactly with your requirement: return True unless both columns are NaN):
import pandas as pd import numpy as np # Your original DataFrame df = pd.DataFrame({'61 - 90': [np.NaN, 14, np.NaN, 9, 34, np.NaN], '91 and over': [np.NaN, 10, np.NaN, 1, np.NaN, 9]}) # Create the 'not_na' column df['not_na'] = df[['61 - 90', '91 and over']].notna().any(axis=1)
Breakdown:
notna()converts each value toTrueif it’s non-null,Falseif it’s NaN.any(axis=1)scans across each row (axis=1) and returnsTrueif at least one value in the row isTrue.
Method 2: Use isna() + all(axis=1) (negated)
This method first checks if both values in the row are NaN, then negates the result to get your desired boolean output:
df['not_na'] = ~df[['61 - 90', '91 and over']].isna().all(axis=1)
Breakdown:
isna()converts each value toTrueif it’s NaN,Falseotherwise.all(axis=1)returnsTrueonly if both values in the row areTrue(i.e., both are NaN).- The
~operator flips the result, so we getFalseonly when both columns are NaN.
Both methods will produce this output:
61 - 90 91 and over not_na 0 NaN NaN False 1 14.0 10.0 True 2 NaN NaN False 3 9.0 1.0 True 4 34.0 NaN True 5 NaN 9.0 True
内容的提问来源于stack exchange,提问作者Michael Mathews Jr.

