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

如何提取Pandas DataFrame列表型列中的元素?

提取Pandas DataFrame列表类型列的元素

问题说明

你的DataFrame中Rule列混合了单元素列表与字符串类型的值,需要将列表中的唯一元素提取出来,同时保留原字符串值:

输入示例代码:

import pandas as pd
df = pd.DataFrame({'Rule': [["zero"],["a,b,c"], "d"]})

对应的初始DataFrame:

Rule
0   [zero]
1   [a,b,c]
2   d

期望输出结果:

Rule
0   zero
1   a,b,c
2   d

两种可行解决方案

方案1:apply结合类型判断

通过lambda函数逐个判断元素类型,若是列表则取第一个元素,否则保持原值:

df['Rule'] = df['Rule'].apply(lambda x: x[0] if isinstance(x, list) else x)

方案2:利用Pandas str索引+fillna

这种方法更简洁高效:对列表列使用str[0]会直接提取元素,非列表值会返回NaN,再用原列值填充这些NaN即可:

df['Rule'] = df['Rule'].str[0].fillna(df['Rule'])

两种方法都能达成目标,方案2在处理大数据量时性能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:32:04