熊猫:将列拆分为具有唯一值的多列
问题内容:
说我有以下数据框:
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_dummies
与reindex
所有可能的类别:
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