用字符串数据重塑数据框 pandas - 没有类似的答案

reshape dataframe pandas with string data - no similar answers

给定的数据帧格式如下:

Name      Attribute      Answer
Joe       One            Yes
Joe       Two            No
Joe       Two            More info
Mary      One            Left undone
Mary      Three          No response
Mary      One            Too late

我已经尝试了 pivot、pivotable、unstack 等版本来 'unmelt' 从长格式到宽格式的数据。我要找的结果是这样的:

Name       One                        Two                Three
Joe        Yes                        No, More info      Null
Mary       Left undone, Too late      Null               No response

本质上,我需要将属性列中的所有唯一值放入列 headers,然后每个唯一命名人员的属性列中的值就是答案列中的值

我敢肯定有一些重塑魔法我还没有充分拼凑起来,但是典型的方法和阅读超过 20 个 'reshape data long to wide' 的关于 SO 的问题并不重要。

我在两个小时左右前提出了这个问题,有人关闭了它声称它已经得到回答。好吧,检查了每个假设的答案,none 成功了。所以,我的问题还没有得到回答。仅供参考。

尝试:

df.groupby(['Name','Attribute'])['Answer'].agg(lambda x: ', '.join(x)).unstack().reset_index()

输出:

Attribute  Name                    One        Three            Two
0           Joe                    Yes          NaN  No, More info
1          Mary  Left undone, Too late  No response            NaN