简体   繁体   English

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

[英]How to create all possible combinations of pandas columns?

Consider the following pandas DF:考虑以下 pandas DF:

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

How can I create all the possible combination sums of all the values of each pandas dataframe?如何创建每个 pandas dataframe 的所有值的所有可能组合总和? For example:例如:

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

Any idea of how to get all the possible sum/column combinations values in new columns?知道如何在新列中获取所有可能的总和/列组合值吗?

Use itertools.combinations with f-string s for format of new columns names: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

Solution with list comprehension , concat and DataFrame.join for append to original:将 append 的list comprehensionconcatDataFrame.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM