gpt4 book ai didi

python - 使用 Pandas 将数据框中的多列转换为两个新列

转载 作者:行者123 更新时间:2023-12-03 21:49:06 27 4
gpt4 key购买 nike

我在 python pandas 环境中工作:D
目前,我有一个如下所示的数据框:

 0   1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18
ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 ex9 ex10 ex11 ex12 ex13 ex14 ex15 ex16 ex17 ex18
我的目标是使数据框看起来像这样:
 0   1   2   3   4   5  6    7   8   category   amount   
ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 9 ex9
ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 10 ex10
ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 11 ex11
ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 12 ex12
ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 13 ex13
ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 14 ex14
ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 15 ex15
ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 16 ex16
ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 17 ex17
ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 18 ex18
基本上,我希望最后 9 列标题和值在 2 个新列上成为它们自己的行,同时保持前 8 列和行相同。我知道这意味着数据将被复制。
我在 stackoverflow 上看到了一些其他答案,将以下代码用于较小的数据帧,但它对我不起作用:
df.melt(['Type', 'Class'], var_name='Date', value_name='Value')

(df.set_index(['Type', 'Class'])
.stack()
.rename_axis(['Type', 'Class', 'Date'])
.reset_index(name='Value')
)
任何和所有的帮助表示赞赏!
谢谢

最佳答案

你快到了 melt

df.melt(id_vars=df.columns[:9], var_name='category', value_name='amount')

Out[469]:
0 1 2 3 4 5 6 7 8 category amount
0 ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 9 ex9
1 ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 10 ex10
2 ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 11 ex11
3 ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 12 ex12
4 ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 13 ex13
5 ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 14 ex14
6 ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 15 ex15
7 ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 16 ex16
8 ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 17 ex17
9 ex0 ex1 ex2 ex3 ex4 ex5 ex6 ex7 ex8 18 ex18

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

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