【问题标题】:Pandas: split column into multiple columns with unique valuesPandas:将列拆分为具有唯一值的多列
【发布时间】:2018-04-16 15:26:43
【问题描述】:

假设我有以下数据框:

   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

寻找任何建议。

【问题讨论】:

  • 只是装傻?
  • df = pd.get_dummies(df['A']) 应该可以正常工作。
  • 不,它没有。示例:如果您要处理多个文件,则虚拟对象仅获取一个文件中的实例。示例:如果我没有 Irene,则 Irene 不会出现在 dummy 中。但我需要其他文件中的艾琳!明白我的意思了吗?
  • 你的例子,不清楚,请考虑修改

标签: python pandas multiple-columns


【解决方案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

【讨论】:

  • 如果一行中有“我、我自己和艾琳”,逗号是分隔符,会发生什么?
  • @FaCoffee - 那么更好str.get_dummies - df = pd.DataFrame({'A':['Me, Myself, and Irene']}) print (df.A.str.get_dummies(', '))
猜你喜欢
  • 1970-01-01
  • 2020-12-31
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 2023-02-17
  • 2017-10-03
相关资源
最近更新 更多