You need to enable JavaScript to run this app. 如何对Pandas DataFrame指定列内的每个列表元素执行去重操作
优惠活动
大模型
产品
解决方案
定价
更多

如何对Pandas DataFrame指定列内的每个列表元素执行去重操作

Pandas num_ent列逐行列表去重方案

方法1:保序去重(推荐)

Python 3.7及以上版本默认支持字典键保序,使用dict.fromkeys可以在去重的同时保留列表元素原有出现顺序:

df['num_ent'] = df['num_ent'].apply(lambda x: list(dict.fromkeys(x)))

如果使用Python 3.7以下版本,可以调用collections.OrderedDict实现相同效果:

from collections import OrderedDict
df['num_ent'] = df['num_ent'].apply(lambda x: list(OrderedDict.fromkeys(x)))

方法2:无序快速去重

如果不需要保留列表原有元素顺序,可以直接用集合去重,写法更简洁:

df['num_ent'] = df['num_ent'].apply(lambda x: list(set(x)))

处理后输出结果

id                                          num_ent
0    287                      [0, 1, 2, 3, 4, 5, 6, 7]
1   3345                       [1, 2, 3, 4, 5, 6, 7, 8]
2   3967   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
3   7083   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
4  23607         [0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

内容的提问来源于stack exchange,提问作者Luis Felipe Martínez Heredia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 18:06:10