0

I wanna transpose columns in conditions like this.

df = pd.DataFrame({"Product" : ["A", "A", "A", "B", "B", "B", "C", "C", "C"],
              "Question" : ["What", "When", "Where", "What", "When", "Where", "What", "When", "Where"],
              "Answer" : ["Car", "Friday", "German", "Bike", "Wednesday", "France", "Train", "Sunday", "America"]})

enter image description here

enter image description here

Can anyone suggest an effective solution for this case?

Corralien
  • 109,409
  • 8
  • 28
  • 52

1 Answers1

1

Use pivot:

out = df.pivot('Product', 'Question', 'Answer') \
        .reset_index().rename_axis(columns=None)
print(out)

# Output
  Product   What       When    Where
0       A    Car     Friday   German
1       B   Bike  Wednesday   France
2       C  Train     Sunday  America

Check How can I pivot a dataframe

Corralien
  • 109,409
  • 8
  • 28
  • 52