Restructure dataframe - divide one columns' value into multiple columns by condition

Viewed 30

I've been trying to figure this out for over 3 months now... I would like to divide one columns' value into multiple columns by condition. I took many approaches but none of them worked so far... So far I tried;

  • groupby
  • pivot
  • filter

This is data that I have↓↓

My data below background:

  • This is question&answer data

  • Each Section_ID have 3 respondents

  • I would like to divide each "Question" and "Answer" into 3 separate columns in order to see the consensus between 3

  • Under "Section_ID", each respondents' questions and answers are unique

  • Other: Question's data is equal to Answer's data (Question=Answer) Each Section_ID&Interview_date has the same value repeated

    Question Answer Section_ID Interview_date
    DD AB X Y
    DD AB X Y
    DD AB X Y
    BD BG X Y
    BD BG X Y
    KY GG X Y
    KY GG X Y
    KY GG X Y
    KY GG X Y
    RR FR Z Q
    HU RT Z Q
    HU RT Z Q
    HU RT Z Q
    YU GE Z Q
    YU GE Z Q

(This table goes on much longer) This is what I would like to make based on original data↓↓

What I would like to do:

  • Create new columns (divide each "Question" and "Answer" into 3 separate columns, original Section_ID and Interview_date can remain the same)

  • Assign Question&Answer's values into different columns

  • I would like Section_ID and Interview_date aligned the longst value;

  • Add blank if the columns(Question&Answer) doesn't have any more values

    Question_1 Answer_1 Question_2 Answer_2 Question_3 Answer_3 Section_ID Interview_date
    DD AB BD BG KY GG X Y
    DD AB BD BG KY GG X Y
    DD AB Blank Blank KY GG X Y
    Blank Blank Blank Blank KY GG X Y
    RR FR HU RT YU GE Z Q
    Blank Blank HU RT YU GE Z Q
    Blank Blank HU RT Blank Blank Z Q

(This table goes on much longer)

Sorry for selfish request... and thank you for reading!

0 Answers
Related