如何为 pandas 中的多个变量按列创建所有组合? [英] How to create all combinations column wise for multiple variables in pandas?

查看:59
本文介绍了如何为 pandas 中的多个变量按列创建所有组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于n个变量的给定范围.我以n = 3为例.

For a given range for n variables. I have taken n=3 as an example.

A : [1,3]
B:  [5,10,12]
C: [100,113]

请注意,上述范围内的值也可以是浮点数.

Note the values in the above range can be float as well.

我们如何创建一个数据框,其中每一列代表输入变量的唯一组合?

How can we create a dataframe where every column represent a unique combination of the input variables?

    c1  c2  c3  c4  c5  c6  c7  c8  c9  c10 c11 c12
a   1   1   1   3   3   3   1   1   1   3   3   3
b   5   10  12  5   10  12  5   10  12  5   10  12
c   100 100 100 100 100 100 113 113 113 113 113 113

推荐答案

使用Itertools.product,我可以创建列表的所有组合,然后您可以将每个组合写入DataFrame

Using Itertools.product I can make all combinations of a list, afterwards you can write each combination to your DataFrame

import itertools

A = [1, 3]
B = [5, 10, 12]
C = [100, 113]

a = [A, B, C]

print(list(itertools.product(*a)))
# Outputs [(1, 5, 100), (1, 5, 113), (1, 10, 100), (1, 10, 113), (1, 12, 100), (1, 12, 113), (3, 5, 100), (3, 5, 113), (3, 10, 100), (3, 10, 113), (3, 12, 100), (3, 12, 113)]


idx = ['c{}'.format(i) for i in range(1, len(data)+1)]
data = list(itertools.product(*a))
df = pd.DataFrame(data, index=idx, columns=list('abc')).T

df

    c1   c2   c3   c4   c5   c6   c7   c8   c9  c10  c11  c12
a    1    1    1    1    1    1    3    3    3    3    3    3
b    5    5   10   10   12   12    5    5   10   10   12   12
c  100  113  100  113  100  113  100  113  100  113  100  113

这篇关于如何为 pandas 中的多个变量按列创建所有组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆