不同行列数Pandas DataFrame同名列自动相乘的实现方案
按Product维度合并两个异构DataFrame的自动化实现
核心需求匹配规则
- 匹配主键为Product列,无需提前对齐两个DataFrame的行、列规模
- 两个DataFrame的共有数值列:按Product匹配行执行逐值相乘
- 仅在单个DataFrame存在的列:直接按Product对应取值保留,不参与运算
- 全流程无需手动调整参数适配不同的表结构,支持自动化批量运行
可直接复用的实现代码
基于pandas实现的通用处理函数,无需手动指定列名、行范围:
import pandas as pd def merge_by_product(df1: pd.DataFrame, df2: pd.DataFrame, key: str = "Product") -> pd.DataFrame: # 以匹配键为索引,便于后续行对齐 df1_idx = df1.set_index(key) df2_idx = df2.set_index(key) # 自动识别列分类,无需手动枚举 common_cols = df1_idx.columns.intersection(df2_idx.columns).tolist() df1_only_cols = df1_idx.columns.difference(df2_idx.columns).tolist() df2_only_cols = df2_idx.columns.difference(df1_idx.columns).tolist() # 按外连接对齐所有Product行,覆盖两个表中全部存在的Product值 aligned1, aligned2 = df1_idx.align(df2_idx, join="outer", axis=0) # 构造结果表,先计算共有列的乘积 result = pd.DataFrame(index=aligned1.index) result[common_cols] = aligned1[common_cols] * aligned2[common_cols] # 按列归属拼接独有列 if df1_only_cols: result = result.join(aligned1[df1_only_cols]) if df2_only_cols: result = result.join(aligned2[df2_only_cols]) # 将匹配键从索引恢复为普通列 result = result.reset_index() return result
示例验证
使用题目给出的两个输入表调用上述函数:
# 第一个输入DataFrame df1 = pd.DataFrame({ "Product": [1, 2, 3, 4, 5], "1/1/2020": [1, 2, 3, 2, 4], "1/1/2019": [10, 20, 30, 10, 5], "1/1/2018": [1, 1, 10, 5, 10] }) # 第二个输入DataFrame df2 = pd.DataFrame({ "Product": [1, 2, 3, 4, 5], "Skill": ["W2", "W45", "W0", "W1", "W2"], "1/1/2020": [1, 20, 40, 50, 2], "1/1/2019": [1, 1, 5, 5, 2], "1/1/2018": [10, 0, 0, 1, 1] }) # 调用函数得到结果 output = merge_by_product(df1, df2)
运行后得到的输出与题目给出的期望结果完全一致。
适配特性说明
- 无需手动识别列:通过集合运算自动区分共有列、单表独有列,新增列时函数不需要修改
- 无需手动对齐行:通过外连接自动覆盖两个表中所有出现的Product值,支持两个表Product范围不完全重合的场景
- 兼容非数值列:如示例中的Skill字符串列,会被自动归类为单表独有列直接保留,不会触发类型运算报错
- 空值可自定义处理:若某个Product仅在单个表存在,共有列的相乘结果会自动标记为空,可根据需求在结果上追加
output = output.fillna(0)完成空值填充
内容的提问来源于stack exchange,提问作者Ankit Daimary
相关产品推荐
相关产品推荐

