如何在包含多个列的pandas数据帧中生成所有可能的列组合?

2024-04-25 12:36:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

   A  B  C
0  1  3  3
1  1  9  4
2  4  6  3

我想创建这些列的每个可能的唯一组合,而不重复,这样我就可以得到一个包含以下数据的数据帧:a、B、C、a+B、a+C、B+C、a+B+C。我不想让任何列在任何组合中重复,例如a+a+B+C或a+B+B+C。在

我还希望数据框中的每一列都用相关变量名进行标记(例如,对于A+B的组合,列名应为“A_B”)

这是所需的数据帧:

^{pr2}$

使用itertools只需使用3个变量,这就相对容易了,我使用了以下代码来实现:

    import pandas as pd
    import itertools

    combos_2 = pd.DataFrame({'{}_{}'.format(a, b):
    df[a] + df[b] 
    for a, b in itertools.combinations(df.columns, 2)})

    combos_3 = pd.DataFrame({'{}_{}_{}'.format(a, b, c):
    df[a] + df[b] + df[c] 
    for a, b, c in itertools.combinations(df.columns, 3)})

    composites = pd.concat([df, combos_2, combos_3], axis=1)

但是,我不知道如何以pythonic的方式扩展此代码,以解释具有更大列数的DataFrame。有没有一种方法可以使下面的代码更加python,并扩展它以用于大量列?或者有没有更有效的方法来生成这些组合?在


Tags: columns数据方法代码in标记importformat
2条回答

我们需要首先基于列创建combination,然后创建数据帧

from itertools import combinations
input = df.columns
output = sum([list(map(list, combinations(input, i))) for i in range(len(input) + 1)], [])
output
Out[21]: [[], ['A'], ['B'], ['C'], ['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B', 'C']]
df1=pd.DataFrame({'_'.join(x) : df[x].sum(axis=1 ) for x in output if x !=[]})
df1
Out[22]: 
   A  B  C  A_B  A_C  B_C  A_B_C
0  1  3  3    4    4    6      7
1  1  9  4   10    5   13     14
2  4  6  3   10    7    9     13

你很亲密:

from itertools import chain, combinations

# Need to realize the generator to make sure that we don't
# read columns from the altered dataframe.
combs = list(chain.from_iterable(combinations(d.columns, i)
                                 for i in range(2, len(d.columns) + 1)))
for cols in combs:
    df['_'.join(cols)] = df.loc[:, cols].sum(axis=1)

有一点需要注意的是,如果将列与_组合,而列名本身可以包含_,那么迟早会有列名冲突的。在

相关问题 更多 >