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

如何按Person分组合并词表DataFrame并补全词项计数

问题描述

我有一个包含person、word、count字段的DataFrame,需要对照词表word_df检查每位person包含的词语:存在的词count为1,不存在的为0,最终生成每位person对应所有词项的完整记录。

示例数据

import pandas as pd

df = pd.DataFrame({
    'person': [1, 1, 1, 2, 3, 4, 4, 4, 4],
    'word': ['apple', 'orange', 'pear', 'apple', 'grape', 'orange', 'apple', 'pear', 'berry'],
    'count': [1, 1, 1, 1, 1, 1, 1, 1, 1]
})

word_list = ['apple', 'orange', 'pear', 'berry', 'grape']
word_df = pd.DataFrame({'word': word_list})

期望输出

result_df = pd.DataFrame({
    'person': [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4],
    'word': ['apple', 'orange', 'pear', 'berry', 'grape', 
             'apple', 'orange', 'pear', 'berry', 'grape', 
             'apple', 'orange', 'pear', 'berry', 'grape', 
             'orange', 'apple', 'pear', 'berry', 'grape'],
    'count': [1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0]
})
解决方法

核心是先构造所有person与词表的笛卡尔积,再关联原数据填充count值:

  1. 提取所有唯一的person,和词表生成笛卡尔积,得到每位person对应所有词项的基础框架
  2. 用左连接关联原DataFrame,保留所有框架记录
  3. 将缺失的count值填充为0,整理格式

具体代码:

import pandas as pd

# 生成所有person与word的笛卡尔积
person_df = pd.DataFrame({'person': df['person'].unique()})
cross_df = pd.merge(person_df, word_df, how='cross')

# 左连接原数据,填充缺失的count为0并整理格式
result_df = pd.merge(cross_df, df, on=['person', 'word'], how='left') \
              .fillna({'count': 0}) \
              .astype({'count': int}) \
              .sort_values(['person', 'word']) \
              .reset_index(drop=True)

print(result_df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:56:16