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

使用Pandas筛选含特定整数的集合列行及后续数据处理

解决方案

步骤1:筛选包含特定整数的行

先构造示例数据(可替换为你实际的DataFrame),再通过布尔索引筛选出VALUES列集合包含目标整数(以12为例)的行:

import pandas as pd

# 构造示例DataFrame
data = {
    'VALUES': [
        {2624, 1383, 2855, 1871, 16784, 9811, 2970},
        {2898, 12, 1871, 223},
        {2624, 2855, 519, 15662, 1230, 1871, 2970},
        {2624, 12, 55, 519, 313, 1230, 10588, 2970},
        {1230, 55, 89564, 1247}
    ]
}
df = pd.DataFrame(data)

# 定义目标整数
target_num = 12

# 筛选包含目标数的行
filtered_df = df[df['VALUES'].apply(lambda x: target_num in x)]

执行后得到筛选结果:

VALUES
1           {2898, 12, 1871, 223}
3          {2624, 12, 55, 519, 313, 1230, 10588, 2970}

步骤2:新增列并转换集合为列表

给筛选后的DataFrame添加NEW_COL列,同时将VALUES列的集合转为列表并移除目标整数:

# 添加NEW_COL列,赋值为目标整数
filtered_df['NEW_COL'] = target_num

# 处理VALUES列:转列表并移除目标数
filtered_df['VALUES'] = filtered_df['VALUES'].apply(lambda x: list(x - {target_num}))

最终输出结果:

VALUES  NEW_COL
1           [2898, 1871, 223]       12
3          [2624, 55, 519, 313, 1230, 10588, 2970]       12

补充说明

  • 集合是无序结构,转列表后的元素顺序可能和示例有差异,但元素内容准确;若需要固定顺序,可转列表后排序,比如list(sorted(x - {target_num}))。
  • 若需防御性处理(比如避免未筛选干净的行报错),可修改apply逻辑为list(x - {target_num}) if target_num in x else x。

内容的提问来源于stack exchange,提问作者Mr.Slow

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:10:36