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

Python实现字符串与另一列子串匹配并转Pandas DataFrame需求

解决方法:匹配子串并生成字典/Pandas DataFrame

Hey there! Let's work through this step by step—since you're new to Python, I'll break down both the pure Python dictionary approach and the Pandas DataFrame method, and explain why your original code might have been throwing errors.

1. 纯Python字典实现

如果不需要用Pandas,直接用基础Python就能构建匹配结果字典。核心思路是遍历每个匹配词,然后筛选出所有包含它的名称:

matches = ['cat','bat','fat']
names = ['turtle','bigcats','hfat1']

# 初始化空字典存储结果
match_results = {}

for match_word in matches:
    # 用列表推导式筛选包含当前匹配词的名称
    matched_names = [name for name in names if match_word in name]
    match_results[match_word] = matched_names

# 打印结果
print(match_results)

运行后输出:

{'cat': ['bigcats'], 'bat': [], 'fat': ['hfat1']}

这里要注意:你之前尝试用name.str.contains(...),但str.contains是Pandas Series专属方法,普通Python字符串不能直接用这个方法。普通字符串判断子串用match_word in name就足够啦。

2. Pandas DataFrame实现

如果需要生成带对应列的DataFrame,我们可以用Pandas的str.contains方法(这次要确保是对Series对象调用),有两种常见的输出格式:

格式一:每行名称对应所有匹配词的标记列

这种格式会给每个匹配词新增一列,标记该行名称是否包含该词:

import pandas as pd

matches = ['cat','bat','fat']
names = ['turtle','bigcats','hfat1']

# 创建基础DataFrame
df = pd.DataFrame({'names': names})

# 遍历每个匹配词,添加对应列
for word in matches:
    df[f'contains_{word}'] = df['names'].str.contains(word)

# 查看结果
print(df)

输出:

names  contains_cat  contains_bat  contains_fat
0     turtle         False         False         False
1    bigcats          True         False         False
2     hfat1         False         False          True

格式二:长格式的匹配对DataFrame

如果想要直接展示匹配词-对应名称的配对关系,可以生成一个长表格:

import pandas as pd

matches = ['cat','bat','fat']
names = ['turtle','bigcats','hfat1']

# 收集所有匹配对
match_pairs = []
for match_word in matches:
    for name in names:
        if match_word in name:
            match_pairs.append({'match_word': match_word, 'matched_name': name})

# 转换为DataFrame
result_df = pd.DataFrame(match_pairs)

print(result_df)

输出:

match_word matched_name
0        cat      bigcats
1        fat       hfat1

为什么你的原代码报错?

你提到用了for x in matches: if name.str.contains(...),大概率是因为name是普通的Python字符串(从names列表里遍历出来的单个元素),而str.contains只能用于Pandas的Series对象(也就是DataFrame的一列)。如果要在Pandas里用这个方法,必须对df['names']这种Series调用,而不是单个字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:33:32