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

pandas DataFrame场景下AttributeError未按预期运行问题咨询

pandas列值判断累加逻辑不生效原因分析

核心问题原因

  • 错误调用isnull()方法:pandas的isnull()是Series、DataFrame等容器对象的方法,从行中取出的单个浮点值(无论是否为NaN)属于numpy标量类型,没有isnull()成员方法,所以无论Quantity Long是否为空,row.loc["Quantity Long"].isnull()都会触发AttributeError,直接进入except分支,永远不会执行累加Quantity Short的逻辑。
  • 缺少返回值判断:即使isnull()可以正常调用,你的代码也没有对该方法的返回布尔值做判断,只要方法调用不报错,无论Quantity Long是否为空,都会直接累加Quantity Short,和预期逻辑完全不符。
  • iterrows()使用错误:iterrows()迭代返回的元组结构为(行索引, 行数据),你定义的(col, row)变量名不符合实际返回结构,虽然未使用第一个变量暂时不影响运行,但属于语法使用错误。

修正后代码

直接使用pandas全局空值判断函数pd.isna()处理单个值的空值判断,无需异常捕获:

from collections import defaultdict
import pandas as pd

"""
creating dict of {symbol:[spot, aggregate]
"""
abn_dict = defaultdict(lambda: [0, 0])

for idx, row in abn_df.iterrows():
    symbol = row.loc["Symbol"]
    if pd.isna(row.loc["Quantity Long"]):
        # Quantity Long为空时累加Short值
        abn_dict[symbol][1] += row.loc["Quantity Short"]
    else:
        # Quantity Long非空时累加Long值
        abn_dict[symbol][1] += row.loc["Quantity Long"]

内容的提问来源于stack exchange,提问作者Bamir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:27:04