使用每列中的所有字符串数据旋转 Pandas 数据框

问题描述

示例数据框:

Name   Attribute     Response
Joe    A             Yes
Joe    B             smoking 
Joe    B             headache
Mary   A             Null
Mary   B             Never
Bob    C             Today
Mary   A             Tomorrow

我已经尝试了几个小时并搜索了所有明显相似的 SO 问题,以将此 df 转换为以下所需的输出。注意,Joe 和 Mary 有不止一行属性相同,但响应不同。

期望的输出

Name    A                    B                     C
Joe    Yes                   smoking,headache     Null
Mary   Null,tomorrow        Never                 Null
Bob    Null                  Null                  Today

再次重申,我已经查看了所有关于从长到宽重塑数据帧的 SO 响应,但没有一个涉及这个精确的问题。此外,这些响应中的每一个都涉及我实施的答案,并且都导致了错误,无论是值错误还是数据错误,尤其是指出索引包含重复值的错误。因此,非常感谢您的帮助。

解决方法

您可以使用 .pivot_table() 执行 aggfunc=list

print(
    df.pivot_table(
        index="Name",columns="Attribute",aggfunc=list,fill_value="Null"
    ).droplevel(0,axis=1)
)

打印:

Attribute                 A                    B        C
Name                                                     
Bob                    Null                 Null  [Today]
Joe                   [Yes]  [smoking,headache]     Null
Mary       [Null,Tomorrow]              [Never]     Null

或者如果您不想要列表:

print(
    df.pivot_table(
        index="Name",aggfunc=",".join,fill_value="Null",).droplevel(0,axis=1)
)

打印:

Attribute              A                 B      C
Name                                             
Bob                 Null              Null  Today
Joe                  Yes  smoking,headache   Null
Mary       Null,Tomorrow             Never   Null

编辑:重命名索引:

df = df.pivot_table(
    index="Name",)

df.index.name = ""
df.columns.name = ""