简体   繁体   English

动态创建熊猫数据框中的所有列组合

[英]Dynamically create all column combinations in a pandas data frame

I have a data frame df with columns and string values in it. 我有一个带有列和字符串值的数据框df My goal is to create a data frame final_df whose columns represent all possible combinations of the df 's columns including their values (ideally separated by a _ [not in the sample code]). 我的目标是创建一个数据框final_df其列表示df列的所有可能组合,包括它们的值(理想情况下用_分隔[不在示例代码中])。

Example Code: 示例代码:

import pandas as pd
from  itertools import combinations

d = {'AAA': ["xzy", "gze"], 'BBB': ["abc", "hja"], 'CCC': ["dfg", "hza"], 'DDD': ["hij", "klm"], 'EEE': ["lal", "opa"]}
df = pd.DataFrame(data=d)

# two combinations
cc = list(combinations(df.columns,2))
df_2 = pd.concat([df[c[0]] + df[c[1]] for c in cc], axis=1, keys=cc)
df_2.columns = df_2.columns.map(''.join)

# three attributes
del cc
cc = list(combinations(df.columns,3))
df_3 = pd.concat([df[c[0]] + df[c[1]] + df[c[2]] for c in cc], axis=1, keys=cc)
df_3.columns = df_3.columns.map(''.join)

# four attributes
del cc
cc = list(combinations(df.columns,4))
df_4 = pd.concat([df[c[0]] + df[c[1]] + df[c[2]] + df[c[3]] for c in cc], axis=1, keys=cc)
df_4.columns = df_4.columns.map(''.join)

# five attributes
del cc
cc = list(combinations(df.columns,5))
df_5 = pd.concat([df[c[0]] + df[c[1]] + df[c[2]] + df[c[3]] + df[c[4]] for c in cc], axis=1, keys=cc)
df_5.columns = df_5.columns.map(''.join)

# join dataframes
dfs = [df, df_2, df_3, df_4, df_5]
final_df = dfs[0].join(dfs[1:])

Is there a Pythonic way to dynamically create such a final_df data frame, depending on the number of columns? 有没有一种Python方法可以根据列数动态创建这种final_df数据帧?

I thought of a solution, however... the column names will not change. 我想到了一个解决方案,但是...列名不会更改。

def combodf(dfx, x): 
    d = (['_'.join(i) for i in zip(*a)] for a in combinations(df.T.values.tolist(), x)) 
    return pd.DataFrame(d).T 

final_df = pd.concat([df, *(combodf(df, i) for i in range(2,6))], 1) 

But looking at your "column" structure it would just make more sense to have them as values. 但是,查看您的“列”结构,将它们作为值会更有意义。 So here is a workaround where we move the column to the last row. 所以这是一种解决方法,我们将列移到最后一行。

import pandas as pd
from itertools import combinations

def combodf(dfx, x):
    d = [['_'.join(i) for i in zip(*a)] for a in combinations(df.T.values.tolist(), x)]
    return pd.DataFrame(d).T

d = {
'AAA': ["xzy", "gze"], 
'BBB': ["abc", "hja"], 
'CCC': ["dfg", "hza"], 
'DDD': ["hij", "klm"], 
'EEE': ["lal", "opa"]
}

df = pd.DataFrame(data=d)
df.loc[len(df)] = df.columns # insert columns last row
df = pd.concat([df, *(combodf(df, i) for i in range(2,6))], 1)
df.columns = df.tail(1).values[0] # make last row columns
df = df.drop(2) # drop last row

Comparison: 比较:

print((df == final_df).all().all()) # True
print((df.columns == final_df.columns).all()) # True

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

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