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

如何按部分匹配字符串分组表格行并对数值列求和?

如何对包含部分匹配字符串的行分组并求和?

原始数据

ArtistPoints
Notorious BIG34
Notorious BIG feat. blah blah42
2pac20
Dr.Dre feat. 2pac30

预期结果

ArtistPoints
Notorious BIG76
2pac50

方法一:Excel 实现

1. 使用 SUMIF 函数(关键词明确场景)

假设原始数据在A2:B5区域,将目标关键词("Notorious BIG"、"2pac")放在D2、D3单元格,在E2输入公式:

=SUMIF(A:A, "*"&D2&"*", B:B)

回车后下拉填充到E3,即可得到对应关键词的求和结果。

解释:*是通配符,代表任意长度字符,*"&D2&"*"表示匹配所有包含D2内容的行,再对B列数值求和。

2. 使用 Power Query 批量处理(更灵活)

  • 选中数据区域,点击「数据」选项卡 → 「从表格/区域」,导入Power Query编辑器
  • 添加自定义列,输入公式提取核心艺人名称:
    if Text.Contains([Artist], "Notorious BIG") then "Notorious BIG" else if Text.Contains([Artist], "2pac") then "2pac" else [Artist]
    
  • 选中新增的自定义列和Points列,点击「转换」选项卡 → 「分组依据」,选择自定义列为分组依据,操作选「求和」,目标列选Points
  • 点击「关闭并上载」,即可得到分组求和后的表格。

方法二:Python(Pandas)实现

用pandas库可以快速完成批量处理:

import pandas as pd

# 构造原始数据(实际可通过pd.read_excel/pd.read_csv读取文件)
data = {
    "Artist": ["Notorious BIG", "Notorious BIG feat. blah blah", "2pac", "Dr.Dre feat. 2pac"],
    "Points": [34, 42, 20, 30]
}
df = pd.DataFrame(data)

# 定义需要匹配的关键词列表
keywords = ["Notorious BIG", "2pac"]

# 新增分组列,匹配对应的核心艺人
def match_group(artist):
    for kw in keywords:
        if kw in artist:
            return kw
    return artist

df["Group"] = df["Artist"].apply(match_group)

# 分组求和并整理格式
result = df.groupby("Group")["Points"].sum().reset_index()
result.columns = ["Artist", "Points"]

print(result)

运行后输出结果:

Artist  Points
0  Notorious BIG      76
1           2pac      50

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:45:46