Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert multiple binary columns into crosstab

I am trying to convert the following dataset which has multiple binary variables into a crosstab.

df = pd.DataFrame({'colour_blue': [1, 0, 1], 'colour_green': [0, 1, 1],
                   'colour_red': [1, 1, 0], 'emotion_happy': [1, 1, 1],'emotion_angry': [0, 1, 1], 'emotion_sad': [0, 0, 1]})

into the following crosstab but i am having no luck

emotion blue green red
happy 2 2 2
angry 1 2 1
sad 1 1 0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is matix multiplication:

df.filter(like='emotion').T @ df.filter(like='colour')

Output:

               colour_blue  colour_green  colour_red
emotion_happy            2             2           2
emotion_angry            1             2           1
emotion_sad              1             1           0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading