'Conditional Transpose in Pandas [duplicate]

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?



Solution 1:[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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1