2

This should be an easy question, but for some reason I can't find the answer online. I have a DataFrame column that consists of dummy variables:

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

What I want is a 4x4 data frame that looks like

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

I've tried using get_dummies to no results:

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 and making the column into a series of lists doesn't work either. What should I do?

3 Answers 3

3

You can try this:

# 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

Sign up to request clarification or add additional context in comments.

Comments

2

This will skip your initial step of foo to foo1 and get you straight there from foo

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.