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

如何移除Pandas DataFrame列表列中不含下划线的元素?

移除Pandas DataFrame列中列表内不含下划线的元素

原始数据

import pandas as pd
w = pd.DataFrame({'Column A': ['Cell 1', 'Cell 2', 'Cell 3'], 'Column B': [['a_1', 'a'], ['b1', 'b2'], ['c_1','c_2', 'c3']]})

期望结果

Column A        Column B
0   Cell 1        [a_1]
1   Cell 2        []
2   Cell 3        [c_1, c_2]

实现方法

  • 方法一:lambda函数快速筛选
    直接用apply遍历Column B的每个列表,通过列表推导式只保留包含下划线的元素:
w['Column B'] = w['Column B'].apply(lambda x: [item for item in x if '_' in item])
  • 方法二:自定义函数(可读性更强)
    如果需要更清晰的代码结构,可单独定义筛选函数再通过apply调用:
def keep_underscore_items(lst):
    return [item for item in lst if '_' in item]

w['Column B'] = w['Column B'].apply(keep_underscore_items)

运行上述任意一种方法后,打印w即可得到目标结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:07:03