这里我有一个表(它真的很大,我只是举一个简化的例子)
import pandas as pd
indices = (1,2,3,4)
columns = ["id", "height1", "height2", "height3"]
data = (["xxx1", 1, 2, 3], ["xxx2", 4, 5, 6], ["xxx3", 7, 8, 9], ["xxx4", 10, 11, 12])
df = pd.DataFrame(data, index = indices, columns = columns)
df
但是,如果我想让这个dataframe以这种方式显示,该怎么办呢? 我尝试使用 groupby(id) 然后使用 unstack() 但失败了。
欢迎任何帮助或提示
id height score
xxx1 height1 1
xxx1 height2 2
xxx1 height3 3
xxx2 height1 4
xxx2 height2 5
.
.
.
xxx4 height3 12
最佳答案
让我们尝试融化
df.melt('id')
id variable value
0 xxx1 height1 1
1 xxx2 height1 4
2 xxx3 height1 7
3 xxx4 height1 10
4 xxx1 height2 2
5 xxx2 height2 5
6 xxx3 height2 8
7 xxx4 height2 11
8 xxx1 height3 3
9 xxx2 height3 6
10 xxx3 height3 9
11 xxx4 height3 12
关于python - 如何将这个数据框改得更长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69458578/