2017-04-21 127 views
2

这应该是一个简单的问题,但由于某种原因,我无法在线找到答案。我有一个包含虚拟变量的数据框柱:如何将二进制变量的DataFrame列变成多列虚拟变量

import pandas as pd 

foo = pd.Series([6,7,8,3]) 
foo1 = bob.apply(lambda x: bin(x)[2:].zfill(4)) 
foo1 

0 0110 
1 0111 
2 1000 
3 0011 

我要的是一个4x4的数据帧,看起来像

A B C D 
0 1 1 0 
0 1 1 1 
1 0 0 0 
0 0 1 1 

我使用get_dummies没有结果的尝试:

foo1.str.get_dummies() 

0110 0111 1000 0011 
1 0 0 0 
0 1 0 0 
0 0 1 0 
0 0 0 1 

str.split使列成为一系列列表也不起作用。我该怎么办?

回答

3

你可以试试这个:

# convert the series to str type; 
# extract all characters with regex .; 
# unstack to wide format 
foo1.astype(str).str.extractall('(.)')[0].unstack() 

enter image description here

2

这将跳过你的foo初始步骤foo1foo

foo.apply(lambda x: pd.Series(list('{:04b}'.format(x)))) 

    0 1 2 3 
0 0 1 1 0 
1 0 1 1 1 
2 1 0 0 0 
3 0 0 1 1 
2
In [49]: pd.DataFrame(foo1.apply(list).values.tolist()) 
Out[49]: 
    0 1 2 3 
0 0 1 1 0 
1 0 1 1 1 
2 1 0 0 0 
3 0 0 1 1 
让你直有