How to pivot survey/questionnaire data and count multiple option questions?

Viewed 100

I'm trying to pivot a survey with many questions all sharing the same levels. Basically I want to pivot from this:

Customer Atribute 1 Atribute 2 Atribute 3
1 A B A
2 B B A
3 C B C

To this:

Product Atribute 1 Atribute 2 Atribute 3
A 1 0 2
B 1 3 0
C 1 0 1

In my real data I have dozens of columns and levels (A, B, C...Z) and hundreds of customers. I was once able to do this in R but it was years ago with an overcomplicated algorithm. I'm wondering if Python/pandas has an easy fix for this.

1 Answers

I suppose your DataFrame named df, then you can do it in this way:

import pandas as pd

df.apply(pd.Series.value_counts).fillna(0).astype(int).drop("Customer" , axis=1).rename_axis("Product")

this gives me:
enter image description here

Related