如何按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值:
- 提取所有唯一的person,和词表生成笛卡尔积,得到每位person对应所有词项的基础框架
- 用左连接关联原DataFrame,保留所有框架记录
- 将缺失的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
相关产品推荐
相关产品推荐

