gpt4 book ai didi

python - 将列转换为 Pandas 数据框中的表头

转载 作者:太空宇宙 更新时间:2023-11-04 04:35:46 24 4
gpt4 key购买 nike

我有这个数据框:

identifier_1         measure         Value     identifier_2
abc height 12 oii
abc weight 122 oii
abc eye_color green Oii
cde height 43 lkj
cde weight 123 lkj
cde eye_color blue lkj
fgh height 32 mnb
fgh weight 125 mnb
fgh eye_color black mnb

我想将“measure”列转换为表头,并将列值中的相应单元格作为其值,例如:

identifier_1    height  weight  eye_color   identifier_2
abc 12 122 green oii
cde 43 123 blue lkj
fgh 32 125 black mnb

我尝试了 pandas 中的 pivot 函数,但无法达到所需的结果。

最佳答案

使用set_indexunstack :

df1 = (df.set_index(['identifier_1','identifier_2','measure'])['Value']
.unstack()
.reset_index()
.rename_axis(None, axis=1))
print (df1)
identifier_1 identifier_2 eye_color height weight
0 abc oii green 12 122
1 cde lkj blue 43 123
2 fgh mnb black 32 125

关于python - 将列转换为 Pandas 数据框中的表头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51768103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com