Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a dataframe with grouped questions from three columns

I have the following dataframe:

       A               B                  C
  I am motivated     Agree                4
  I am motivated     Strongly Agree       5
  I am motivated     Disagree             6
  I am open-minded   Agree                4
  I am open-minded   Disagree             4
  I am open-minded   Strongly Disagree    3

Where column A is the question, column B is the answer, and column C is the frequency of "Strongly Agree", "Agree", "Disagree", and "Strongly Disagree" for the questions in column A.

How can I convert it into the following dataframe?

                  Strongly Agree    Agree     Disagree   Strongly Disagree
I am motivated        5               4           6             0
I am open-minded      0               4           4             3

I tried looking at groupby() for columns from other posts but could not figure it out. Using python 3

like image 864
yangd01234 Avatar asked Feb 04 '23 12:02

yangd01234


1 Answers

Use DataFrame.pivot_table() method:

In [250]: df.pivot_table(index='A', columns='B', values='C', aggfunc='sum', fill_value=0)
Out[250]:
B                 Agree  Disagree  Strongly Agree  Strongly Disagree
A
I am motivated        4         6               5                  0
I am open-minded      4         4               0                  3
like image 111
MaxU - stop WAR against UA Avatar answered Feb 08 '23 08:02

MaxU - stop WAR against UA