You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas中对两列应用lambda函数判断非全NaN时遇ValueError

Solution for Checking Non-Null Rows in Pandas DataFrame

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 to True if it’s non-null, False if it’s NaN.
  • any(axis=1) scans across each row (axis=1) and returns True if at least one value in the row is True.

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 to True if it’s NaN, False otherwise.
  • all(axis=1) returns True only if both values in the row are True (i.e., both are NaN).
  • The ~ operator flips the result, so we get False only 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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 16:17:28