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

如何统计第一个DataFrame元素在第二个DataFrame字符串中的出现次数?

问题:统计DF1元素在DF2字符串列中的出现次数

现有DataFrame(记为DF1):

items
0   apple
1   car
2   tree
3   house
4   light
5   camera
6   laptop
7   watch
8   other

需要统计DF1中的每个元素,在另一个DataFrame(DF2)的items字符串列中的出现次数,DF2结构如下:

id        items
0   555       wall, grass, apple
1   124       bag, coffee, light
2   23123     bag, none, game
3   666       none, none, none

期望得到结果:

items    count
0   apple    1
1   car      0
2   tree     0
3   house    0
4   light    1
5   camera   0
6   laptop   0
7   watch    0
8   other    0

解决方案

可以通过以下步骤实现:

  • 拆分DF2的items列,将每个字符串中的元素单独展开
  • 统计展开后所有元素的出现频次
  • 将统计结果与DF1做左连接,把未出现元素的计数填充为0

具体代码实现

import pandas as pd

# 构造示例数据
df1 = pd.DataFrame({'items': ['apple', 'car', 'tree', 'house', 'light', 'camera', 'laptop', 'watch', 'other']})
df2 = pd.DataFrame({
    'id': [555, 124, 23123, 666],
    'items': ['wall, grass, apple', 'bag, coffee, light', 'bag, none, game', 'none, none, none']
})

# 拆分DF2的items列,展开为单个元素
df2_exploded = df2['items'].str.split(', ', expand=True).stack().reset_index(drop=True).to_frame(name='items')

# 统计频次
counts = df2_exploded['items'].value_counts().reset_index()
counts.columns = ['items', 'count']

# 和DF1左连接,填充缺失值为0
result = df1.merge(counts, on='items', how='left').fillna(0)
result['count'] = result['count'].astype(int)

print(result)

代码说明

  • str.split(', ', expand=True)将每个字符串按, 拆分生成多列,stack()把多列转成单行元素,reset_index清理冗余索引
  • value_counts()自动统计每个元素的出现次数
  • merge(how='left')保证DF1的所有元素都被保留,fillna(0)把未出现元素的计数设为0,最后转成整数类型保证结果格式符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:18:27