本文详解如何在 Pandas DataFrame 中通过 `apply` 调用两个字符串选择函数,并安全拼接其结果,重点解决因 NaN/None 或空字符串导致的 `TypeError: boolean value of NA is ambiguous` 问题。
该错误的根本原因在于:Pandas 中的 != “” 等布尔比较操作无法直接作用于包含 NaN(或 pd.NA)的 Series。当 df[‘NLT’] 某行值为 NaN 时,df[‘NLT’] != “” 返回的是一个三态布尔对象(pd.BooleanDtype),其本身不能被 if 语句直接求值——这正是报错 “boolean value of NA is ambiguous” 的来源。
✅ 正确做法:使用 pandas.isna() 或 str.len() > 0 显式判断
推荐改写函数,避免对可能含缺失值的列直接做 != “” 比较:
import pandas as pd
import numpy as np
def a(df):
# 使用 pd.isna() 安全判断是否为空(兼容 NaN、None、pd.NA)
if pd.notna(df['NLT']) and str(df['NLT']).strip() != "":
return df['NLT']
else:
return df['LT']
def b(df):
if pd.notna(df['NCC']) and str(df['NCC']).strip() != "":
return df['NCC']
else:
return df['CC']
? 补充说明:str(df[‘NCC’]) 是防御性写法,确保即使遇到非字符串类型(如数字、None)也能转为字符串再判断;strip() 可过滤纯空白字符串(如 ” “)。
✅ 更高效写法(向量化,无需 apply)
apply 在逐行处理时性能较低,且易出错。更推荐使用 numpy.where 或 pandas.Series.fillna() + combine_first() 实现向量化逻辑:
# 替代函数 a:优先取 NLT,为空则取 LT
df['ra'] = df['NLT'].where(df['NLT'].str.strip().astype(bool), df['LT'])
# 替代函数 b:优先取 NCC,为空则取 CC
df['rb'] = df['NCC'].where(df['NCC'].str.strip().astype(bool), df['CC'])
# 安全拼接(自动跳过 NaN:NaN + 'str' → NaN;但可进一步填充)
df['RR'] = (df['ra'].fillna("") + df['rb'].fillna(""))
⚠️ 注意: