旋转 pandas 数据框,每列中包含所有字符串数据
pivoting pandas dataframe with all string data in each column
示例数据框:
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 有不止一行 Attribute 相同,但响应不同。
期望的输出
Name A B C
Joe Yes smoking, headache Null
Mary Null, tomorrow Never Null
Bob Null Null Today
再次重申,我已经查看了每一个关于将数据帧从长到宽重塑的 SO 响应,其中 none 涉及这个精确的问题。此外,这些响应中的每一个都涉及我实施的答案,并且都导致错误,值错误或数据错误,尤其是指出索引包含重复值的错误。因此,感谢您的帮助。
你可以用 aggfunc=list
做 .pivot_table()
:
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",
columns="Attribute",
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",
columns="Attribute",
aggfunc=",".join,
fill_value="Null",
)
df.index.name = ""
df.columns.name = ""
示例数据框:
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 有不止一行 Attribute 相同,但响应不同。
期望的输出
Name A B C
Joe Yes smoking, headache Null
Mary Null, tomorrow Never Null
Bob Null Null Today
再次重申,我已经查看了每一个关于将数据帧从长到宽重塑的 SO 响应,其中 none 涉及这个精确的问题。此外,这些响应中的每一个都涉及我实施的答案,并且都导致错误,值错误或数据错误,尤其是指出索引包含重复值的错误。因此,感谢您的帮助。
你可以用 aggfunc=list
做 .pivot_table()
:
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",
columns="Attribute",
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",
columns="Attribute",
aggfunc=",".join,
fill_value="Null",
)
df.index.name = ""
df.columns.name = ""