How to unstack unique column values to columns and set another column as row index in Python Pandas

Viewed 63

I have a table as given below.

enter image description here

I am trying to rearrange the table in a certain manner so that I have the unique values of the column 'Metric Category' as separate columns and the corresponding values from the 'Response' column as values. Though I have been able to solve till here with the following code

df2.set_index([df2.groupby(['Metric_Category'])['Metric_Category'].cumcount(), 'Metric_Category'])['Response'].unstack()

enter image description here

However, I am unable to figure out how to add the corresponding 'Participant' name alongside the responses as follows.

enter image description here

1 Answers

Add column Participant to MultiIndex:

df2.set_index(['Participant',df2.groupby(['Metric_Category'])['Metric_Category'].cumcount(), 'Metric_Category'])['Response'].unstack()
Related