0

I am prety sure that there is a pandas function to do so but I could not find it when I was looking at the documentation and googled it. Maybe you can help me. Here is what I want to do:

import pandas as pd

data = {'col1': ['val1','val2','val3'],
        'col2': ['feat1','feat1','feat2']
       }
df = pd.DataFrame(data)
print (df)

>    col1   col2
> 0  val1  feat1
> 1  val2  feat1
> 2  val3  feat2

and I want to have the dataframe with this shape:

>    col1  feat1  feat2
> 0  val1      1      0
> 1  val2      1      0
> 2  val3      0      1

Best P

1
  • 1
    You need .get_dummies() method. Commented Sep 11, 2020 at 13:09

2 Answers 2

1
print(pd.get_dummies(df.set_index('col1'), prefix='', prefix_sep=''))

Prints:

      feat1  feat2
col1              
val1      1      0
val2      1      0
val3      0      1
Sign up to request clarification or add additional context in comments.

Comments

0

You can also use crosstab

pd.crosstab(df.col1, df.col2)

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.