Convert column of lists to columns of True/False if it belongs to the lists

Viewed 91

I have the following DataFrame

    Codice  Sem CFU Rating  Gruppo
0   51132   1   10  0.0 [STAT]
1   51197   1   5   0.0 [ING]
2   52354   1   5   0.0 [ING]
3   52496   1   10  0.0 [MST]
4   52498   2   10  0.0 [MST]
... ... ... ... ... ...
57  97667   1   8   3.0 [MTM]
58  97673   2   8   0.0 [MTM]
59  97683   2   5   5.0 [STAT, ING]
60  97690   2   12  0.0 [MST]
61  97725   2   10  0.0 [CSCL, MTM]

As you see, the Gruppo column is made of lists of a finite number of unique elements. I'm trying to generate from this a DF to be used in pulp for something like "if Codice belongs to Gruppo", thus I need a DF (or matrix, but I wanted to indexise using Codice and not just an ordinary integer) made like this:

    Codice  STAT    ING ... MST
0   51132   True    False   ... False
1   51197   False   True    ... False

Basically True/False whether the corresponding list contains ING,STAT,MST,...

1 Answers

General solution if Codice are or not unique use DataFrame.explode with crosstab and test if not 0:

df1 = df.explode('Gruppo')
df2 = pd.crosstab(df1['Codice'], df1['Gruppo']).ne(0).reset_index()

Or use MultiLabelBinarizer with aggregate max and compare for equal 1:

from sklearn.preprocessing import MultiLabelBinarizer

mlb = MultiLabelBinarizer()
df2 = (pd.DataFrame(mlb.fit_transform(df['Gruppo']),
                    columns=mlb.classes_, 
                    index=df['Codice']).groupby(level=0).max().eq(1))

If values in Codice are unique is possible remove aggregation:

from sklearn.preprocessing import MultiLabelBinarizer

mlb = MultiLabelBinarizer()
df2 = (pd.DataFrame(mlb.fit_transform(df['Gruppo']),
                    columns=mlb.classes_, 
                    index=df['Codice']).eq(1))
Related