python - Pandas:将列拆分为具有唯一值的多列

标签 python pandas multiple-columns

假设我有以下数据框:

   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

关于python - Pandas:将列拆分为具有唯一值的多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49860987/

相关文章:

python - 在 python 中替换 char 以引用的最佳方法

python - 如何更改 QMainWindow 边框和标题栏的颜色?

python - 如何返回类型提示定义的类型

python - dataframe.to_hdf() 中的参数键是什么意思

html - 如何使 div float 在分栏文本上

Python输出奇怪的字节数组

python - 带有重复标题值的 Pandas read_excel

python - 将多个列表写入 CSV 中单个单元格中的不同列

python - 重命名 pandas 数据框的列名称未按预期工作 - python

替换 data.frame 列中的某些值