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

如何在DataFrame中筛选含≤7类型值的行(多值列处理)

解决方法

直接用pandas的apply方法配合自定义函数就能搞定,步骤如下:

1. 构造原始DataFrame

先把你的数据转换成pandas可处理的格式:

import pandas as pd

df = pd.DataFrame({
    'A': ['AAC', 'AAD', 'AAS', 'AAG', 'AAC'],
    'Variant&Price': ['7:124|25: 443', '35:|35:', '32:98|3:40', '2: |25:', '25:443|26:344'],
    'Qty': [1, 1, 1, 1, 1]
})

2. 写判断函数

这个函数负责检查每个单元格里是否存在≤7的类型:

def has_valid_type(s):
    # 按|分割所有条目
    items = s.split('|')
    for item in items:
        # 提取冒号前的类型部分,去掉前后空格
        type_str = item.split(':')[0].strip()
        # 确保是数字再转成整数判断
        if type_str.isdigit():
            if int(type_str) <= 7:
                return True
    return False

3. 筛选行

用apply把函数应用到Variant&Price列,生成布尔索引筛选数据:

filtered_df = df[df['Variant&Price'].apply(has_valid_type)]
print(filtered_df)

运行后输出的结果就是你要的筛选后DataFrame:

A    Variant&Price  Qty
0  AAC  7:124|25: 443    1
2  AAS    32:98|3:40    1
3  AAG      2: |25:      1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 10:40:27