简体   繁体   中英

Pandas: split column into multiple columns with unique values

Say I have the following dataframe:

   A
0  Me
1  Myself
2  and
3  Irene
4  Me, Myself, and Irene

which needs to be turned into:

   Me  Myself  and  Irene
0  1   0       0    0
1  0   1       0    0
2  0   0       1    0
3  0   0       0    1
4  1   1       1    1

Looking for any suggestion.

You can use get_dummies with reindex by all possible categories:

df1 = pd.DataFrame({'A': ['Me', 'Myself', 'and', 'Irene']})
df2= pd.DataFrame({'A': ['Me', 'Myself', 'and']})
df3 = pd.DataFrame({'A': ['Me', 'Myself', 'or', 'Irene']})

all_categories = pd.concat([df1.A, df2.A, df3.A]).unique()
print (all_categories)
['Me' 'Myself' 'and' 'Irene' 'or']

df1 = pd.get_dummies(df1.A).reindex(columns=all_categories, fill_value=0)
print(df1)
   Me  Myself  and  Irene  or
0   1       0    0      0   0
1   0       1    0      0   0
2   0       0    1      0   0
3   0       0    0      1   0

df2 = pd.get_dummies(df2.A).reindex(columns=all_categories, fill_value=0)
print(df2)
   Me  Myself  and  Irene  or
0   1       0    0      0   0
1   0       1    0      0   0
2   0       0    1      0   0

df3 = pd.get_dummies(df3.A).reindex(columns=all_categories, fill_value=0)
print(df3)
   Me  Myself  and  Irene  or
0   1       0    0      0   0
1   0       1    0      0   0
2   0       0    0      0   1
3   0       0    0      1   0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM