Any method to do auto-multiclass?

Viewed 34

The purpose to gather random label is to see the difference between 2-3 clusters, and I am going to do machine learning(random forest) later.

So the question is, I want to concat label0 and label1 to one group, label2 and label3 to another group.

enter image description here

Then, random change the order of the label, like label0 with label2, label1 with label3,...and so on. I don't know how to do it automatically.

The expected result is like this

enter image description here The expected result is like this

Any solution? Thanks

1 Answers

I think I got a solution to your problem:

import pandas as pd
import random

data = {
    'col1': [0, 1, 2, 3, 4, 5, 6, 7],
    'col2': [7, 6, 5, 4, 3, 2, 1, 0],
    'label': ['0', '0', '1', '1', '2', '2', '3', '3']
}
df = pd.DataFrame(data=data)
labels = list(df['label'].unique())

num_iterations = 10
for i in range(10):
    random.shuffle(labels)
    dfs = []
    for j in range(1, len(labels), 2):
        series = df[(df['label'] == labels[j-1]) | (df['label'] == labels[j])][['col1', 'col2']].agg('sum')
        new_label = labels[j-1] + ' ' + labels[j]
        new_df = series.to_frame().T.assign(label=new_label)
        dfs.append(new_df)
    shuffeled_df = pd.concat(dfs)

So I first take a list of the labels and shuffel it. Then selecting pairwise the labels and calculating the sum. This is done for all label pairs (in this iteration). At the end a new combined DataFrame will be created.

Related