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

如何筛选DataFrame中第二个括号后含指定关键词的行?

解决方案

你可以通过正则表达式结合pandas的str.contains()方法实现该筛选需求,核心是精准匹配第二个右括号后的关键词内容,同时兼容大小写和空格差异。

实现代码

import numpy as np
import pandas as pd

data = {
    'Names': ['Store (007) Total amount of Sales ',
              'Store perc (65) Total amount of sales ',
              'Mall store, aid (005) Total amount of sales',
              'Increase in the value of sales / Additional seling (22) Total amount of sales',
              'Dividends (0233) Amount of income tax',
              'Other income (098) Total amount of Sales',
              'Other income (0245) Amount of Income Tax',
              ],
    'Sales': [10,10,9,7,5,5,5],
}

df = pd.DataFrame(data, columns=['Names', 'Sales'])

# 构造正则:匹配到第二个右括号后,内容包含目标关键词(忽略大小写)
pattern = r'.*\).*\)(?=.*Total amount of sales)'
filtered_df = df[df['Names'].str.contains(pattern, case=False, regex=True)]

print(filtered_df)

代码说明

  • 正则表达式.*\).*\)(?=.*Total amount of sales):
    • .*\):匹配任意字符直到第一个右括号
    • .*\):继续匹配任意字符直到第二个右括号
    • (?=.*Total amount of sales):正向预查,确保第二个右括号后的内容包含目标关键词
  • case=False:忽略大小写,同时匹配「Total amount of Sales」和「Total amount of sales」
  • regex=True:告知str.contains()启用正则匹配规则

运行结果

会筛选出5行符合条件的数据,自动排除不包含目标关键词的2行记录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:35:26