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

使用Pandas从多组中随机选行生成组合的实现方法

问题描述

有一个Pandas DataFrame df,示例结构如下(真实数据包含更多列与group):

group  sub  fruit
a      1    apple
a      2    banana
a      3    orange
b      1    pear
b      2    strawberry
b      3    cherry
c      1    kiwi
c      2    tomato
c      3    lemon

所有group的行数一致,需要生成一个新的DataFrame:从每个group中选取一行(要覆盖所有可能的组合,示例中共有3×3×3=27种不同组合),最终输出包含combo标识列,格式如下:

combo  group  sub  fruit
1      a      1    apple
1      b      1    pear
1      c      1    kiwi
2      a      2    banana
2      b      2    strawberry
2      c      1    kiwi
3      a      3    orange
3      b      2    strawberry
3      c      1    kiwi
4      a      2    banana
4      b      2    strawberry
4      c      3    lemon
5      a      3    orange
5      b      3    cherry
5      c      3    lemon
...
解决方案

要生成所有group行的笛卡尔积组合,再映射回原数据的信息,可按以下步骤操作:

完整代码

import pandas as pd
import itertools

# 示例数据(替换为你的真实数据即可)
df = pd.DataFrame({
    'group': ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'],
    'sub': [1, 2, 3, 1, 2, 3, 1, 2, 3],
    'fruit': ['apple', 'banana', 'orange', 'pear', 'strawberry', 'cherry', 'kiwi', 'tomato', 'lemon']
})

# 按group分组,获取每个组对应的行索引列表
group_indices = df.groupby('group').groups
index_lists = [list(indices) for _, indices in sorted(group_indices.items())]

# 生成所有组行索引的笛卡尔积(即所有可能的选取组合)
all_combinations = list(itertools.product(*index_lists))

# 构建最终结果DataFrame
result_rows = []
for combo_num, idx_tuple in enumerate(all_combinations, start=1):
    combo_rows = df.loc[list(idx_tuple)].copy()
    combo_rows['combo'] = combo_num
    result_rows.append(combo_rows)

final_df = pd.concat(result_rows, ignore_index=True)
# 调整列顺序,让combo列排在最前面
final_df = final_df[['combo', 'group', 'sub', 'fruit']]

print(final_df)

代码说明

  • df.groupby('group').groups:获取每个group对应的行索引集合,确保能准确定位每行数据
  • itertools.product(*index_lists):直接生成所有组行索引的笛卡尔积,这一步会得到示例中的27种组合
  • 遍历组合时,用df.loc[list(idx_tuple)]取出对应行,添加combo编号后拼接,最后调整列顺序匹配期望输出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:15:31