add binary values to column dataframe based on list

Viewed 517

I have a dataframe 'trips' that looks like this:

    Name  Age      Stops
a   jack   34      [A,B,C]
b   john   30      [B]
c  ralph   31      [A,C]
d   olaf   32      [A,B]     

where the column "Stops" contains lists of stops from [A,B,C] of variable length. I have been able to create 3 additional columns with zero values for A,B,C with:

 for col in list_stops:
     trips[col] = 0

I would like for each row, add a binary values 0/1 to the new columns based on the values of each list such that the new dataframe looks like this:

    Name  Age      Stops    A   B   C
a   jack   34      [A,B,C]  1   1   1
b   john   30      [B]      0   1   0
c  ralph   31      [A,C]    1   0   1
d   olaf   32      [A,B]    1   1   0
2 Answers

I will use sklearn

from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
s=pd.DataFrame(mlb.fit_transform(df['Stops']),columns=mlb.classes_, index=df.index)
df=df.join(s)

If you have pandas 0.25 , we can try explode

df.join(df['Stops'].explode().str.get_dummies().sum(level=0))

Alternative solution with explode and pivot_table:

df = df.explode('Stops').pivot_table(index='Age', columns='Stops', aggfunc='size', fill_value=0).reset_index().rename_axis(None, axis=1)
Related