gpt4 book ai didi

Python dataframe 转置某些行具有多个值的位置

转载 作者:行者123 更新时间:2023-11-28 21:07:07 34 4
gpt4 key购买 nike

我有一个数据框:

field,value
a,1
a,2
b,8

我想把它转成这种形式

a,b  
1,8
2,8

最佳答案

  • set_index 在每个 field 组 + field
  • 上有一个 cumcount
  • unstack + ffill

df.set_index(
[df.groupby('field').cumcount(), 'field']
).value.unstack().ffill().astype(df.value.dtype)

field a b
0 1 8
1 2 8

关于Python dataframe 转置某些行具有多个值的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41887508/

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