简体   繁体   中英

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

I have a table as given below.

在此处输入图像描述

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()

在此处输入图像描述

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

在此处输入图像描述

将列Participant添加到MultiIndex

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM