Pandas: modify columns indicated in another column of type list

Viewed 39

I have a dataframe like the following:

A       B       C       my_list
0       0       0       [A, B]
0       0       0       [B, C]
0       0       0       [A, C]
0       0       0       [A]
0       0       0       [A, C]

I need a dataframe like:

A       B       C       my_list
1       1       0       [A, B]
0       1       1       [B, C]
1       0       1       [A, C]
1       0       0       [A]
1       0       1       [A, C]

That is, filling with 1 values the columns indicated on the 'my_list' column.

How can I do that?

My real dataframe is huge, so performance is important here.

1 Answers

We can re-create the dataframe with explode and str.get_dummies

df.update(df['my_list'].explode().str.get_dummies().sum(level=0))
Related