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

如何将pandas DataFrame每列与另一DataFrame相乘并生成指定规则新列

高效实现Pandas双DataFrame逐值相乘并生成指定命名新列的方法

先给出可直接运行的实现代码,适配你描述的场景:

步骤1:构造示例数据(可跳过)

import pandas as pd

# 第一个DataFrame,索引为数字序列,列如col1、col2
df1 = pd.DataFrame({
    "col1": [1, 2, 3],
    "col2": [4, 5, 6]
}, index=[0, 1, 2])

# 第二个DataFrame,索引为a、b,列为x、y
df2 = pd.DataFrame({
    "x": [10, 20],
    "y": [30, 40]
}, index=["a", "b"])

步骤2:核心实现代码

完全基于numpy广播机制运算,无Python层面循环,处理大表时效率远高于apply、循环拼接等方案:

# 利用广播机制完成逐值相乘
mult_res = df1.to_numpy()[..., None] * df2.to_numpy().T.reshape(1, df2.shape[1], df2.shape[0])

# 生成符合命名规则的列名
new_cols = [
    f"{col1}_{col2}_{idx2}"
    for col1 in df1.columns
    for col2 in df2.columns
    for idx2 in df2.index
]

# 构造最终结果DataFrame
result = pd.DataFrame(
    mult_res.reshape(len(df1), -1),
    index=df1.index,
    columns=new_cols
)

效果验证

以上示例运行后,result的列名会完全符合要求的规则:col1_x_a、col1_x_b、col1_y_a、col1_y_b、col2_x_a、col2_x_b、col2_y_a、col2_y_b,每个单元格的值为对应原数据的乘积。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:09:00