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

ufunc 'add'类型不匹配错误:DataFrame全NaN时的Excel读取问题

问题描述

我有一个DataFrame,部分列含有效值、部分列值为NaN(本质是float类型)。我循环遍历describe和referring列,若某行存在文件名,则读取对应Excel文件并填充DataFrame指定列。代码如下:

for i in range(0,len(table_names)):
    if type(table_names['referring'][i])!=float:
        a = table_names['referring'][i] #if the referring column row has some value, take that value
        b = table_names['columns'][i]   #take the row name from `columns` column
        a = a + '.xlsx'    #this will make the file name which i need to refer to populate data
        product_name = pd.read_excel(a)  #read the file
        product_name = product_name.values.tolist()
        df[b] = product_name    #populate the particular column with the content of the file we just read

但当referring和describe列所有值均为NaN时,执行a = a + '.xlsx'会触发错误:

numpy.core._exceptions._UFuncNoLoopError: ufunc 'add' did not contain a loop with signature matching types (dtype('float64'), ftype('<U5')) -> None

参考过相关问题,但类型转换方案不适用于生成文件名的场景,特此求助。

解决方案

核心问题

你用type(table_names['referring'][i])!=float判断NaN的方式存在漏洞——当referring列全为NaN时,pandas会将整列转为float类型,此时即便进入判断分支,a拿到的仍是float类型的NaN,和字符串拼接必然报错。

改进后的代码

直接用pandas原生的pd.notna()判断非空值,同时用iterrows()遍历行数据,更简洁可靠:

for idx, row in table_names.iterrows():
    # 精准判断referring单元格是否非空
    if pd.notna(row['referring']):
        # 强制转字符串,彻底避免类型问题
        a = str(row['referring']) + '.xlsx'
        b = row['columns']
        product_name = pd.read_excel(a)
        # 明确取Excel第一列数据,保证和df行数匹配
        df[b] = product_name.iloc[:, 0].values

额外优化说明

  • 类型安全:强制把row['referring']转为字符串,杜绝隐式类型转换引发的异常
  • 遍历效率:iterrows()直接迭代每行数据,无需手动处理索引,减少出错概率
  • 数据对齐:用iloc[:,0]指定取Excel的第一列数据,避免因Excel多列导致的维度不匹配问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:56:06