规范化dataframe中具有深度嵌套数据的列

2024-05-21 14:51:14 发布

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

我的问题是从JSON文件中提取的数据,其结构为嵌套数组,如下所示:

data = { "data": [
{
  "insights": {
    "data": [
      {
        "account_id": "10",
        "actions": [
          {
            "action_type": "link",
            "value": "3"
          },
          {
            "action_type": "post",
            "value": "3"
          }
        ],
        "clicks": "3"
      },
      {
        "account_id": "10",
        "actions": [
          {
            "action_type": "save",
            "value": "3"
          }
        ],
        "clicks": "123"
      },
      {
        "account_id": "10",
        "actions": [
          {
            "action_type": "save",
            "value": "1"
          },
          {
            "action_type": "link",
            "value": "11"
          },
          {
            "action_type": "view",
            "value": "10"
          }
        ],
        "clicks": "19"
      },
      {
        "account_id": "10",
        "clicks": "0"
      }
    ],
    "paging": {
      "cursors": {
        "before": "ON",
        "after": "OFF"
      }
    }
  },
  "id": "1"
}]}

我的目标是通过CSV文件将其转换为Python上可读的表。 输出应采用以下形式:

    account_id action_type value clicks id before after
     10            link      3    3     1    ON    OFF 
     10            post      3    3     1    ON    OFF
     10            save      3    123   1    ON    OFF
     10            save      1    19    1    ON    OFF 
     10            link      11   19    1    ON    OFF  
     10            view      10   19    1    ON    OFF
     10            Null      Null 0     1    ON    OFF

我试着用问题Converting a JSON with a nested array to CSV的答案找出一个解决方案

我还尝试了json_normalize,但由于嵌套数组的多个级别,我仍然被卡住了。我使用了以下代码:

    python        
    df = json_normalize(data['data'],record_path=['insights','data'],meta=['id'])

还有两个问题:

  • action列仍然包含嵌套的值,正如您所看到的,每行上的操作类型和值的数量并不相同
  • 前,;“后”列不显示在输出中。我知道我选择了记录路径洞察>;数据,并且这两列在insights>;分页,但我不知道如何或是否可以同时选择两条记录路径

有人看到我遗漏了什么吗


Tags: 文件actionsidjsondatavalueonsave