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

为何Pandas DataFrame使用assign方法调用自定义函数时报错,而循环遍历赋值却正常?

为何Pandas DataFrame使用assign方法调用自定义函数时报错,而循环遍历赋值却正常?

我在使用pandas时遇到了一个奇怪的问题,想搞清楚df.assign(...)方法的具体细节。明明自定义函数是有效的,但尝试用它给列赋值时却抛出了ValueError错误。

我的代码是这样的:

def is_toc_row(row):
    m_sig = m_df.loc[m_df.signature == row.signature]
    pct = (~pd.isnull(m_sig.line_type)).sum() / m_sig.shape[0]
    return (not pd.isnull(row.line_type)) or (pct < .5)


m_df = m_df.assign(is_toc_row=is_toc_row)

运行后得到的报错是:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

但换成循环遍历的方式赋值,就完全正常:

for ind, row in m_df.iterrows():
    m_df.at[ind, 'is_toc_row'] = is_toc_row(row)

我有点疑惑:是不是在函数里引用整个DataFrame有什么问题?我查过相关说明,只提到被操作的DataFrame不能被修改,而我这里并没有修改它啊。

当然我可以写个替代方案,但就是想搞明白为什么assign方法不行,方便以后避坑。

示例数据(部分行)

indexsignatureline_type
0WYcxXTjq27YAP4uJOcLeRLelyUixNJaOwFwf2qqfpM4NaN
1WYcxXTjq27YAP4uJOcLeRLelyUixNJaOwFwf2qqfpM4NaN
2WYcxXTjq27YAP4uJOcLeRLelyUixNJaOwFwf2qqfpM41
3WYcxXTjq27YAP4uJOcLeRLelyUixNJaOwFwf2qqfpM42
4WYcxXTjq27YAP4uJOcLeRLelyUixNJaOwFwf2qqfpM42.4

备注:内容来源于stack exchange,提问作者Chase

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 18:20:34