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

无法使用ast.literal_eval将pandas DataFrame列转为列表的问题

问题解析与解决办法

你没出错!你打印的是整个列(Series)的类型——不管列里存的是字符串还是列表,movie['genres']本身永远是pandas.core.series.Series类型。你的代码其实已经成功把列中的每个字符串元素转换成了包含字典的列表,只是检查方式不对。

正确的验证方式

要确认元素的类型,得检查Series里的单个元素,比如:

print(type(movie['genres'].iloc[0]))

执行后输出应该是<class 'list'>,这就说明转换成功了。

优化建议

你的列数据是标准JSON格式,用json.loads处理会更贴合场景,同时记得处理可能的空值避免报错:

import json
import pandas as pd

movie = pd.read_csv("tmdb_5000_movies.csv")
# 处理空值,确保转换不会失败
movie['genres'] = movie['genres'].apply(lambda x: json.loads(x) if pd.notna(x) else [])
print(type(movie['genres'].iloc[0]))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:55:25