问题描述
给定这种格式的数据帧:
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 等版本来将这些数据从长格式“解冻”到宽格式。我正在寻求的结果是这样的:
Name One Two Three
Joe Yes No,More info Null
Mary Left undone,Too late Null No response
本质上,我需要将 Attribute 列中的所有唯一值都设为列标题,然后将每个唯一命名人员的 Attribute 列中的值设为 Answer 列中的值
我确信我还没有充分拼凑出一些重塑魔法,但是典型的方法和阅读 20 多个关于 SO 的“从长到宽的重塑数据”问题并不切题。
我在大约两个小时前提出了这个问题,有人关闭了它,声称它已经得到了回答。 Welp,经历了每个假设的答案,但没有一个成功。所以,我的问题还没有得到解答。仅供参考。
解决方法
试试:
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