在Pandas DataFrame中查找字符串:统计Jan列值在URL列的出现情况
解决DataFrame中按列值统计匹配次数的问题
嘿,我来帮你搞定这个统计需求!先把你要的三列逻辑掰扯清楚:
- found in cell:当前行
Jan列的值,在该行URL单元格里出现的次数 - found in column:当前行
Jan列的值,在整个URL列所有单元格中的总出现次数 - distinct finds:当前行
Jan列的值,在URL列中多少不同的行里出现过(只要某行URL包含该值就算1次,不管该行内重复出现多少次)
下面用Python的pandas一步步实现,我先构造示例数据,你可以直接替换成自己的DataFrame来用:
1. 准备示例数据
先导入pandas并创建测试用的数据集,方便你验证效果:
import pandas as pd # 构造示例DataFrame,替换成你自己的数据即可 data = { 'Jan': ['try', 'why', 'try', 'hello'], 'URL': [ 'https://example.com/try-this', 'https://example.com/why-not-why', 'https://example.com/another-try', 'https://example.com/no-match' ] } df = pd.DataFrame(data)
2. 计算found in cell列
针对每行,统计Jan的值在对应URL单元格里的出现次数,用apply逐行处理就行:
df['found in cell'] = df.apply(lambda row: row['URL'].count(row['Jan']), axis=1)
3. 计算found in column列
先统计每个Jan值在整个URL列的总出现次数,再把结果映射到DataFrame的新列中:
# 生成每个Jan值的总出现次数字典 total_match_counts = {} for term in df['Jan'].unique(): total_match_counts[term] = df['URL'].str.count(term).sum() # 把统计结果映射到新列 df['found in column'] = df['Jan'].map(total_match_counts)
4. 计算distinct finds列
统计每个Jan值在多少行的URL中出现过(只要该行包含至少一次就算):
# 生成每个Jan值的出现行数字典 distinct_row_counts = {} for term in df['Jan'].unique(): distinct_row_counts[term] = df['URL'].str.contains(term).sum() # 映射到新列 df['distinct finds'] = df['Jan'].map(distinct_row_counts)
最终结果
运行完上面的代码后,你的DataFrame会变成这样:
Jan URL found in cell found in column distinct finds 0 try https://example.com/try-this 1 2 2 1 why https://example.com/why-not-why 2 2 1 2 try https://example.com/another-try 1 2 2 3 hello https://example.com/no-match 0 0 0
额外小提示
如果需要忽略大小写匹配(比如把Try和try当成同一个值),只需要把字符串统一转成小写再统计,比如修改found in cell的代码:
df['found in cell'] = df.apply(lambda row: row['URL'].lower().count(row['Jan'].lower()), axis=1)
其他两列的统计逻辑也可以用同样的方式修改哦~
内容的提问来源于stack exchange,提问作者Ni_Tempe
相关产品推荐
相关产品推荐

