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

如何对pandas中字符串格式的列表使用explode函数实现行拆分

解决方案

你当前answer列中类似["Trustful", "Curious", "Nervous"]的内容是字符串类型,并非Python列表对象,所以explode方法无法对其做拆分处理,需要先把这类字符串格式的列表转换成真实的列表对象。

方法1:使用ast.literal_eval转换(推荐)

ast模块的literal_eval是专门用来转换Python字面量字符串的方法,安全性高,不会执行任意代码,是这类场景的首选方案。

import pandas as pd
import ast

# 原DataFrame构造代码
df = pd.DataFrame({'questionId':[1, 2],'answer':['["Trustful", "Curious", "Nervous"]', "very good"]})

# 仅转换列表格式的字符串,普通字符串保留
df['answer'] = df['answer'].apply(lambda x: ast.literal_eval(x) if x.startswith('[') else x)

# 执行explode拆分,ignore_index=True可以重置索引,不需要可以去掉
res = df.explode('answer', ignore_index=True)
print(res)

方法2:使用json.loads转换

因为你这里的列表字符串符合JSON数组的格式规范,也可以用json模块的loads方法转换:

import pandas as pd
import json

df = pd.DataFrame({'questionId':[1, 2],'answer':['["Trustful", "Curious", "Nervous"]', "very good"]})

df['answer'] = df['answer'].apply(lambda x: json.loads(x) if x.startswith('[') else x)
res = df.explode('answer', ignore_index=True)
print(res)

两种方法运行后都可以得到你期望的输出结果:

questionId     answer
0           1  Trustful
1           1   Curious
2           1   Nervous
3           2  very good

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:57:02