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

如何对Pandas DataFrame两组列的组合进行相乘运算

实现Pandas列组的所有组合相乘

方法一:利用广播机制(高效简洁)

通过NumPy的广播特性直接实现列的外积运算,代码简洁且性能高效:

import pandas as pd

# 初始化原DataFrame
df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9], 'D':[0,1,2]})

# 定义需要组合的两组列
group1 = ['A', 'B']
group2 = ['C', 'D']

# 广播相乘得到所有组合的结果数组
product_arr = df[group1].values[:, :, None] * df[group2].values[:, None, :]
# 重塑数组结构并生成对应列名,转为DataFrame
output = pd.DataFrame(
    product_arr.reshape(len(df), -1),
    columns=[f"{x}{y}" for x in group1 for y in group2]
)

print(output)

运行输出:

AC  AD  BC  BD
0   7   0  28   0
1  16   2  40   5
2  27   6  54  12

方法二:用itertools生成组合(直观易懂)

如果需要明确看到每一组列的运算过程,可以用itertools.product生成所有列组合,逐个计算乘积:

import pandas as pd
from itertools import product

df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9], 'D':[0,1,2]})

group1 = ['A', 'B']
group2 = ['C', 'D']

output = pd.DataFrame()
# 遍历所有列组合,计算乘积并添加到结果DataFrame
for col1, col2 in product(group1, group2):
    output[f"{col1}{col2}"] = df[col1] * df[col2]

print(output)

该方法与广播机制的输出结果完全一致,适合需要分步验证运算逻辑的场景。


内容的提问来源于stack exchange,提问作者Yun Tae Hwang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:30:12