如何创建pandas列的所有可能组合?

问题描述 投票:0回答:1

考虑以下pandas DF。

col1 col2 col3
1    3     1
2    4     2
3    1     3
4    0     1
2    4     0
3    1     5

我如何创建所有可能的组合和每个pandas数据框的所有值?比如说

col1 col2 col3 col1_col2 col1_col3 col2_col3
1    3     1       4        2        4   
2    4     2       6        4        6
3    1     3       4        6        4
4    0     1       4        5        1
2    4     0       6        2        4
3    1     5       4        8        6

任何想法,如何获得所有可能的sumcolumn组合值在新的列?

python python-3.x pandas itertools
1个回答
4
投票

使用 itertools.combinationsf-string新列名的格式。

from  itertools import combinations

for i, j in combinations(df.columns, 2):
    df[f'{i}_{j}'] = df[i] + df[j]

print (df)
   col1  col2  col3  col1_col2  col1_col3  col2_col3
0     1     3     1          4          2          4
1     2     4     2          6          4          6
2     3     1     3          4          6          4
3     4     0     1          4          5          1
4     2     4     0          6          2          4
5     3     1     5          4          8          6

解决办法是: list comprehension, concatDataFrame.join 用于附加到原件上。

dfs = [(df[i] + df[j]).rename(f'{i}_{j}') for i, j in combinations(df.columns, 2)]
df = df.join(pd.concat(dfs, axis=1))
print (df)
   col1  col2  col3  col1_col2  col1_col3  col2_col3
0     1     3     1          4          2          4
1     2     4     2          6          4          6
2     3     1     3          4          6          4
3     4     0     1          4          5          1
4     2     4     0          6          2          4
5     3     1     5          4          8          6
© www.soinside.com 2019 - 2024. All rights reserved.