简体   繁体   中英

Drop and include columns in a DataFrame in all possible combinations(To train a ML model) except one column(target column)

I expect something like this,

df (original):

   index  feature1(target column)  feature2  feature3  feature4
0      0                        1         2         3         4
1      1                        1         2         3         4
2      2                        1         2         3         4
3      3                        1         2         3         4

df1:

   feature1(target column)  feature2  feature3
0                        1         2         3
1                        1         2         3
2                        1         2         3
3                        1         2         3

df2:

   feature1(target column)  feature2  feature4
0                        1         2         4
1                        1         2         4
2                        1         2         4
3                        1         2         4

df3:

   feature1(target column)  feature3  feature4
0                        1         3         4
1                        1         3         4
2                        1         3         4
3                        1         3         4

df4:

   feature1(target column)  feature2  feature4
0                        1         2         4
1                        1         2         4
2                        1         2         4
3                        1         2         4

Try this and see if it helps:

import itertools
import pandas as pd
df = pd.DataFrame({
    'col1': [1, 2, 3, 4, 5],
    'col2': [1, 2, 3, 4, 5],
    'col3': [1, 2, 3, 4, 5],
    'col4': [1, 2, 3, 4, 5]
})
target_col = ['col4']
iterable = list(set(df.columns.tolist()).difference(target_col))
r = len(iterable) - 1
cmbs = itertools.combinations(iterable, r)
# print(df[iterable])
for item in cmbs:
    features = df[list(item)]
    print(item)
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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