python - 如何将这个数据框改得更长?

标签 python pandas dataframe

这里我有一个表(它真的很大,我只是举一个简化的例子)

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

返回 enter image description here

但是,如果我想让这个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/

相关文章:

python - 训练精度提高但验证精度保持在 0.5,模型预测每个验证样本几乎相同的类

r - 获取需要匹配 R 中其他列的条件的平均值

python - 处理 block 数据时如何 pd.merge(..., on ="column", ...) ?

python - argparse - 每个操作不同的强制/可用参数

python - 记录对 python 对象数据成员中元素的访问

python - Groupby和转置 Pandas , python

python - 使用字典映射数据帧索引

Pandas:什么是 dtype = <U64,如何将其转换为字符串?

python-3.x - 如何快速在pct_change的结果中添加%?

python - 如何检索 NumPy 随机数生成器的当前种子?