gpt4 book ai didi

python - 沿一列从长到宽 reshape DataFrame

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:07 25 4
gpt4 key购买 nike

我正在寻找一种方法将下面的表 A 显示重新配置为表 B。

表A:

type   x1  x2  x3  
A 4 6 9
A 7 4 1
A 9 6 2
B 1 3 8
B 2 7 9

转化为表B:

type   x1  x2  x3  x1'  x2'  x3'  x1'' x2'' x3''  
A 4 6 9 7 4 1 9 6 2
B 1 3 8 2 7 9 NA NA NA

真正的表 A 超过 150000 行和 36 列。具有 2100 个独特的“类型”值。

最佳答案

您可以适本地设置索引,然后unstack:

df

type x1 x2 x3
0 A 4 6 9
1 A 7 4 1
2 A 9 6 2
3 B 1 3 8
4 B 2 7 9

res = (df.set_index(['type', df.groupby('type').cumcount()])
.unstack()
.sort_index(level=-1, axis=1))

res.columns = res.columns.map(lambda x: x[0] + "'" * int(x[1]))
res
x1 x2 x3 x1' x2' x3' x1'' x2'' x3''
type
A 4.0 6.0 9.0 7.0 4.0 1.0 9.0 6.0 2.0
B 1.0 3.0 8.0 2.0 7.0 9.0 NaN NaN NaN

关于python - 沿一列从长到宽 reshape DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55367996/

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