1

I am trying to pivot a dataframe in Python for a school project. I know how to transform the rows into column, but what I don't know is how to populate that new columns with the value 1 or 0 depending the case. For example, now I have something like this:

Code   Product
1       Water
1       Coke
2       Wine
3       Apples

and I want to turn it into something like this:

Code   Water  Coke  Wine  Apples
1       1       1    0      0      
2       0       0    1      0
3       0       0    0      1

I searched the web and I could't find anything. Also, I'm not that advanced in Python language.

Thanks

0

1 Answer 1

2

You can do this with pd.crosstab:

pd.crosstab(index=df.Code, columns=df.Product)

Product   Apples  Coke  Water  Wine
Code                              
1             0     1      1     0
2             0     0      0     1
3             1     0      0     0
Sign up to request clarification or add additional context in comments.

2 Comments

How would you do the opposite! Turn a df that looked like the crosstab into a 1 row/column df?
Check pd.melt @HiFizzle_

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.