将字典列表的字典转换为数据帧

2024-09-26 04:56:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我在下面给出的结构中有一个字典,我需要将它转换成一个数据帧来执行一些聚合操作。但我无法将其转换为给定的输出格式

{
  "raj": [
    {
      "subject": "science",
      "score": "35",
      "create_time": "1595990288421"
    },
    {
      "subject": "maths",
      "score": "40",
      "create_time": "1595980800000"
    }
  ],
  "dev": [
    {
      "subject": "science",
      "score": "23",
      "create_time": "1595990288421"
    }
  ],
  "mag":[
    {
      "subject": "science",
      "score": "41",
      "create_time": "1595990288421"
    },
    {
      "subject": "maths",
      "score": "25",
      "create_time": "1595980800000"
    }
  ]
}

我需要以给定的格式输出数据帧

name    subject     score   create_time
------------------------------------------
raj     science     35      1595990288421
raj     maths       40      1595980800000
dev     science     23      1595990288421
mag     science     35      1595990288421
mag     maths       25      1595980800000

有人能帮我把字典转换成所需的数据帧输出吗


Tags: 数据namedev字典time格式create结构
1条回答
网友
1楼 · 发布于 2024-09-26 04:56:02

使用列表理解

Ex:

df = pd.DataFrame([{'name': k, ** j} for k, v in data.items() for j in v])
print(df)

输出:

  name  subject score    create_time
0  raj  science    35  1595990288421
1  raj    maths    40  1595980800000
2  dev  science    23  1595990288421
3  mag  science    41  1595990288421
4  mag    maths    25  1595980800000

相关问题 更多 >