簡體   English   中英

Pandas:將列拆分為具有唯一值的多列

[英]Pandas: split column into multiple columns with unique values

假設我有以下數據框:

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

這需要變成:

   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

尋找任何建議。

您可以通過所有可能的類別使用get_dummiesreindex

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM