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

如何用Pandas实现DataFrame两列列表元素的全组合配对?

用Pandas实现DataFrame列内元素的笛卡尔积配对

原始DataFrame

colorcars
red, blue, greenBMW, Mercedes
blue, yellowPorsche, Jeep, Volvo

目标DataFrame

colorcars
redBMW
redMercedes
blueBMW
blueMercedes
greenBMW
greenMercedes
bluePorsche
blueJeep
blueVolvo
yellowPorsche
yellowJeep
yellowVolvo

Pandas解决方案

你可以结合str.split()和itertools.product实现需求,无需手动写嵌套循环,代码更简洁且适配DataFrame操作:

import pandas as pd
from itertools import product

# 构造原始DataFrame
df = pd.DataFrame({
    'color': ['red, blue, green', 'blue, yellow'],
    'cars': ['BMW, Mercedes', 'Porsche, Jeep, Volvo']
})

# 1. 将逗号分隔的字符串拆分为元素列表
df['color'] = df['color'].str.split(', ')
df['cars'] = df['cars'].str.split(', ')

# 2. 对每行生成color和cars的笛卡尔积,合并所有结果
result_df = df.apply(
    lambda row: pd.DataFrame(product(row['color'], row['cars']), columns=['color', 'cars']),
    axis=1
).concat()

# 重置索引(可选,让索引从0开始)
result_df = result_df.reset_index(drop=True)

print(result_df)

代码解释

  • str.split(', '):把每行的字符串按, 分割成元素列表,比如"red, blue, green"会转为['red', 'blue', 'green']
  • itertools.product:生成两个列表的笛卡尔积,对应你手动嵌套循环的配对逻辑
  • apply(axis=1):对DataFrame的每一行执行操作,把每行的配对组合转成小DataFrame
  • .concat():把所有行生成的小DataFrame合并成最终的结果DataFrame

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 20:34:56