Create a data block with grouped questions from three columns

I have the following framework:

       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

If column A is a 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 to the next framework?

                  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 couldn't figure it out. Using python 3

+4
source share
2 answers

, , Question/Opinion. , set_index unstack, . . pivot, pivot fill_value, dtype

df.set_index(['A', 'B']).C.unstack(fill_value=0)

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


'B' pd.Categorical,

df.B = pd.Categorical(
    df.B, ['Strongly Disagree', 'Disagree', 'Agree', 'Strongly Agree'], True)
df.set_index(['A', 'B']).C.unstack(fill_value=0)

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

DataFrame.pivot_table():

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
+5

Source: https://habr.com/ru/post/1676316/


All Articles