在 Pandas 中将数据帧转换为长格式

我有一个这样的数据框:

http://img4.mukewang.com/628c365f0001cc1b01860302.jpg

我正在尝试像这样重塑它:


http://img2.mukewang.com/628c366900015a4308720106.jpg

对于我的生活,我无法做到这一点。

我认为 usingdf.pivot_table会起作用,但它对分数进行了某种平均。


我已经搜索过,但找不到类似的问题。大多数重塑问题都不想扩大数据集。


任何建议表示赞赏。


df = [    {'id' : '1', 'score_type': 'test_01', 'score': 1},

          {'id' : '1', 'score_type': 'test_02', 'score': 2},

          {'id' : '1', 'score_type': 'test_03', 'score': 3},

          {'id' : '1', 'score_type': 'test_04', 'score': 4},

          {'id' : '2', 'score_type': 'test_01', 'score': 5},

          {'id' : '2', 'score_type': 'test_02', 'score': 6},

          {'id' : '2', 'score_type': 'test_03', 'score': 7},

          {'id' : '2', 'score_type': 'test_04', 'score': 8}


          ]

df = pd.DataFrame(df)

df = df[['id', 'score_type', 'score']]

df


隔江千里
浏览 131回答 2
2回答

UYOU

df.set_index(['id','score_type']).unstack(-1)

犯罪嫌疑人X

这对你有用:df = df.set_index(['id','score_type']).unstack(-1)df.columns = df.columns.droplevel()score_type  test_01  test_02  test_03  test_04id                                            1                 1        2        3        42                 5        6        7        8让我们详细看一下这两行代码:1. 第一行代码正确格式化了数据框,但'score'在顶部添加了一个额外的级别:df = df.set_index(['id','score_type']).unstack(-1)score                        score_type test_01 test_02 test_03 test_04id                                        1                1       2       3       42                5       6       7       82. 第二行代码允许您删除您不感兴趣的添加级别并获得您正在寻找的结果:df.columns = df.columns.droplevel()score_type  test_01  test_02  test_03  test_04id                                            1                 1        2        3        42                 5        6        7        8
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python