python - 以值作为列进行 JSON 规范化

标签 python json pandas json-normalize

我有以下 JSON;

{
  "data": [
    {
      "gid": "1203715497540179",
      "completed": false,
      "custom_fields": [
        {
          "gid": "1203887422469746",
          "enabled": true,
          "name": "Inputs",
          "description": "",
          "display_value": null,
          "resource_subtype": "text",
          "resource_type": "custom_field",
          "text_value": null,
          "type": "text"
        },
        {
          "gid": "1126427465960522",
          "enabled": false,
          "name": "T-Minus",
          "description": "",
          "display_value": "54",
          "resource_subtype": "text",
          "resource_type": "custom_field",
          "text_value": "54",
          "type": "text"
        }
      ],
      "due_on": "2023-01-25",
      "name": "General Information"
    }
  ]
}

我想用它构建以下 pandas 数据框。基本上我想从 custom_fields 中获取名称并将其设为值为 display_value 的列

name                 due_on         Inputs   T-Minus
General Information  2023-01-25      null      54

我认为这不能通过标准化来完成。所以我开始:

df = pd.json_normalize(test, 
                       record_path =['custom_fields'],
                       record_prefix='_',
                       errors='ignore',
                       meta=['name', 'due_on'])

这让我想到了这样的事情:

_name _display_value name due_on .....(extra fields that I do not need)
Inputs  null         General Information
T-Minus  54          General Information

我现在如何从这个数据框转到我想要的数据框?

最佳答案

pd.json_normalize之后使用pivot:

df = pd.json_normalize(test,  # or test['data']? 
                       record_path =['custom_fields'],
                       record_prefix='_',
                       errors='ignore',
                       meta=['name', 'due_on'])

df = (df.pivot(index=['name', 'due_on'], columns='_name', values='_display_value')
        .reset_index().rename_axis(columns=None))

输出:

>>> df
                  name      due_on Inputs T-Minus
0  General Information  2023-01-25   None      54

关于python - 以值作为列进行 JSON 规范化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75962385/

相关文章:

python - 将列表的成员资格与 True 运算符进行比较

javascript - 打印 JSON 对象的数组

c# - 使用 WCF 将 JSON 对象的一部分序列化和反序列化为字符串

python - 基于 Pandas 条件的行的最大值和最小值(取决于列名)

python - Pandas 从另一列的字符串切片创建新列

python - 如何将存储在 avro 文件中的 org.apache.kafka.connect.data.Decimal 转换为 python 类型?

python - 基本的http文件在python中下载并保存到磁盘?

javascript - 获取 API 数据、呈现数据以及一般使用它的更好方法是什么

javascript - Node js 在异步行为中丢失 : undefined

python - 工作线程内的 Queue.put 失败