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

如何对两个Series执行交叉连接(笛卡尔积)?

解决方案

方法1:直接基于Series构造笛卡尔积结果

通过生成两个Series索引的笛卡尔积MultiIndex,再映射原Series的数值,完全无需转换为DataFrame:

import pandas as pd

# 定义原Series
x = pd.Series([10, 20, 30], index=['a', 'b', 'c'], name='x_value')
y = pd.Series([100, 200], index=['d', 'e'], name='y_value')

# 生成包含双层级的笛卡尔积索引
multi_idx = pd.MultiIndex.from_product([x.index, y.index], names=['x', 'y'])

# 构造结果DataFrame
result = pd.DataFrame({
    x.name: x.repeat(len(y)).values,
    y.name: y.take(range(len(y))).repeat(len(x)).values
}, index=multi_idx)

运行后输出结果:

x_value  y_value
x y
a d        10      100
  e        10      200
b d        20      100
  e        20      200
c d        30      100
  e        30      200

方法2:简洁版(短暂转DataFrame实现交叉合并)

如果可以接受临时转换为单列DataFrame,代码逻辑更直观,最终同样生成目标格式:

# 转单列DataFrame并执行交叉合并
cross_df = x.to_frame().merge(y.to_frame(), how='cross')
# 设置双层级索引
cross_df = cross_df.set_index([x.index.name or 'x', y.index.name or 'y'])
# 统一索引名称(适配原Series索引无名称的情况)
cross_df.index.names = ['x', 'y']

核心说明

  • 两种方法均利用pandas内置方法实现,避免手动遍历,效率更高
  • 方法1完全基于Series操作,满足你“直接处理Series”的需求
  • 最终结果的MultiIndex完整保留了原Series的索引值与层级名称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:55:17