在Python中为非唯一列表创建虚拟对象列

CAr*_*ona 5 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]
Run Code Online (Sandbox Code Playgroud)

我想为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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

使用以下代码根据列的位置为列表中的每个字母生成不同的列.你们有谁知道为什么要这样做?该pd.get_dummies选项也不起作用.

ayh*_*han 4

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
Run Code Online (Sandbox Code Playgroud)

这里,@是未出现在列表中的任意字符。

然后,您可以照常连接:

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
Run Code Online (Sandbox Code Playgroud)