Alfonso_MA
Alfonso_MA

Reputation: 555

Pandas: modify columns indicated in another column of type list

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.

Upvotes: 2

Views: 50

Answers (1)

BENY
BENY

Reputation: 323246

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

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

Upvotes: 3

Related Questions