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

从返回数值数组的SQL查询创建Pandas DataFrame时遇TypeError错误

解决PostgreSQL查询转DataFrame时的TypeError问题

错误原因

查询返回的记录中存在数组字段为NULL的情况,对应代码里的res[0]是None。Pandas在将这类元素转换为DataFrame时,会尝试获取其长度,从而触发TypeError: object of type 'NoneType' has no len()。

修复方案

1. 在代码层过滤无效记录

直接跳过数组为空的记录,再拆分输入特征和分类标签:

cursor.execute(query)
records = cursor.fetchall()
# 筛选出数组非空的有效记录
valid_records = [item for item in records if item[0] is not None]
# 生成特征矩阵X和标签序列y
X = pd.DataFrame([item[0] for item in valid_records])
y = pd.Series([item[1] for item in valid_records])

2. 在SQL查询层提前过滤

修改查询语句,直接排除数组字段为NULL的记录,从源头避免无效数据:

SELECT your_array_col, your_integer_col 
FROM your_table 
WHERE your_array_col IS NOT NULL;

3. 填充空值(业务允许时)

如果不能丢弃记录,可将NULL数组替换为符合要求的默认数组(比如长度300的全0数组):

cursor.execute(query)
records = cursor.fetchall()
# 替换空数组为全0数组,保证长度一致
processed_arrays = [item[0] if item[0] is not None else [0]*300 for item in records]
X = pd.DataFrame(processed_arrays)
y = pd.Series([item[1] for item in records])

内容的提问来源于stack exchange,提问作者Carlos de Armas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 02:23:12