考虑以下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组合值在新的列?
使用 itertools.combinations
与 f-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
, concat
和 DataFrame.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