python - 将非唯一列表的虚拟对象创建到 Python 中的列中

标签 python python-2.7 pandas

目前我有下一个数据框:

import pandas as pd
df= pd.DataFrame({"ID" : ['1','2','3','4','5'], 
                     "col2" : [['a', 'b', 'c'], 
                               ['c', 'd', 'e', 'f'], 
                               ['f', 'b', 'f'], 
                               ['a', 'c', 'b'], 
                               ['b', 'a', 'b']]})

print(df)
  ID          col2
0  1     [a, b, c]
1  2  [c, d, e, f]
2  3     [f, b, f]
3  4     [a, c, b]
4  5     [b, a, d]

我想为 col2 创建一个带有虚拟对象的新数据框,如下所示:

    ID   a   b   c   d   e   f
0   1    1   1   1   0   0   0
1   2    0   0   1   1   1   1
2   3    0   1   0   0   0   1
3   4    1   1   1   0   0   0
4   5    1   1   0   1   0   0

使用以下代码为列列表中的每个字母生成不同的列:

df2= df.col2.str.get_dummies(sep = ",")
pd.concat([data['col1'], df], axis=1)

ID  a   b   b]  c   c]  d   d]  e   f]  [a [b  [c  [f
1   0   1   0   0   1   0   0   0   0   1   0   0   0
2   0   0   0   0   0   1   0   1   1   0   0   1   0
3   0   1   0   0   0   0   0   0   1   0   0   0   1
4   0   0   1   1   0   0   0   0   0   1   0   0   0
5   1   0   0   0   0   0   1   0   0   0   1   0   0

使用以下代码根据列列表中的每个字母所在的位置生成不同的列。你们中有人知道为什么会经历这个吗? pd.get_dummies 选项也不起作用。

最佳答案

str.get_dummies 适用于字符串,因此您可以将您的列表转换为某种分隔的字符串并在该字符串上使用 str_get_dummies。例如,

df['col2'].str.join('@').str.get_dummies('@')
Out: 
   a  b  c  d  e  f
0  1  1  1  0  0  0
1  0  0  1  1  1  1
2  0  1  0  0  0  1
3  1  1  1  0  0  0
4  1  1  0  0  0  0

这里,@是一个没有出现在列表中的任意字符。

然后,您可以像往常一样连接:

pd.concat([df['ID'], df['col2'].str.join('@').str.get_dummies('@')], axis=1)
Out: 
  ID  a  b  c  d  e  f
0  1  1  1  1  0  0  0
1  2  0  0  1  1  1  1
2  3  0  1  0  0  0  1
3  4  1  1  1  0  0  0
4  5  1  1  0  0  0  0

关于python - 将非唯一列表的虚拟对象创建到 Python 中的列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40938810/

相关文章:

python-2.7 - 增加 python 2.7 中的递归限制和堆栈大小

django - uwsgi和django : ImportError: No module named __future__

python 请求给出 'None' 响应,其中需要 json 数据

python - 在pandas系列中设置日期时间值时的SettingWithCopyWarning

python - Pygame 窗口在 Mac 上无法关闭的问题

Python 函数不打印 - 仅存储

python - 计算与 pandas 框架中的条件匹配的行数(如果可能,使用数据的排序)

python - Pandas Dataframe 对象类型

python - Django Rest Framework 可选的嵌套关系

java - 如果涉及方法内变量的范围,python 与 java 有何不同?