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

如何从列表列中提取首个字符串生成新列?

提取列表列的首个元素生成新列

你的genres列已经是列表类型的字段,不需要再用str.split(' ')做分割操作——这个方法是用来处理字符串类型、按空格拆分的,对列表直接用会导致错误。

正确解法

方法1:使用str[0](推荐,Pandas原生支持)

Pandas对包含列表的列可以直接通过str索引取元素:

df_BestBooks['first_genre'] = df_BestBooks['genres'].str[0]

方法2:使用apply自定义逻辑

如果需要处理空列表等异常情况,可以加判断:

df_BestBooks['first_genre'] = df_BestBooks['genres'].apply(lambda x: x[0] if x else None)

原代码错误原因

你原来的代码里df_BestBooks.genres.str.split(' ')是把每个列表当成字符串去按空格分割,但列表本身没有split方法,所以这一步会返回大量NaN,后续通过索引取值自然失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 03:43:10