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

如何将Pandas列中混合类型值转为数组类型?遇ArrowInvalid报错求助

解决Pandas混合类型列转换为统一列表类型的问题

问题分析

你的代码报错有两个核心原因:

  1. 类型判断错误:type(x) == 'str'写法错误,type(x)返回的是<class 'str'>类型对象,和字符串'str'永远不相等,导致字符串元素没有被转换为列表,列中仍混合了字符串和列表类型。
  2. PyArrow类型限制:如果你的Pandas版本是2.0+且启用了PyArrow后端,PyArrow不允许列中同时存在列表和非列表的非空值,混合类型会触发ArrowInvalid错误。

解决方案

方法1:修正列表推导式+类型转换

先将列转为object类型(规避PyArrow的类型限制),再用正确的类型判断逻辑转换元素:

# 转换为object类型(若使用PyArrow dtype则必须)
df['architectural_style'] = df['architectural_style'].astype(object)

# 修正类型判断,将字符串转为单元素列表
df['architectural_style'] = [[x] if isinstance(x, str) else x for x in df['architectural_style']]

方法2:使用apply函数更简洁

apply可以直接对每个元素处理,同时自动兼容类型转换:

df['architectural_style'] = df['architectural_style'].apply(lambda x: [x] if isinstance(x, str) else x)

验证结果

构造测试数据验证:

import pandas as pd

data = {'architectural_style': [[], 'Traditional', ['Courtyard'], ['Contemporary', 'Florida', 'Patio']]}
df = pd.DataFrame(data)

# 执行转换
df['architectural_style'] = df['architectural_style'].apply(lambda x: [x] if isinstance(x, str) else x)

print(df['architectural_style'].tolist())

输出结果符合预期:

[[], ['Traditional'], ['Courtyard'], ['Contemporary', 'Florida', 'Patio']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 04:11:19