Search code examples
pythonpandasdataframepivottranspose

Conditional Transpose in Pandas


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

  • 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