如果属于列表,则将列表列转换为 True/False 的列

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

我有以下 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]

如您所见,Gruppo 列由有限数量的唯一元素列表组成。我正在尝试从中生成一个 DF,用于 pulp 中,用于“如果 Codice 属于 Gruppo”之类的东西,因此我需要一个 DF(或矩阵,但我想要使用 Codice 而不仅仅是普通整数进行索引)像这样:

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

基本上True/False对应列表是否包含ING,STAT,MST,...

一般解决方案如果 Codice 是否唯一使用 DataFrame.explode with crosstab 并测试如果不是 0:

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

或将 MultiLabelBinarizer 与聚合 max 一起使用并比较是否相等 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))

如果 Codice 中的值是唯一的,则可以删除聚合:

from sklearn.preprocessing import MultiLabelBinarizer

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