【问题标题】:How to flatten a JSON to a wide format, in pandas [duplicate]如何在熊猫中将JSON展平为宽格式[重复]
【发布时间】:2021-01-06 01:36:10
【问题描述】:

我有一个 JSON 文件

response ={
  "classifier_id": "xxxxx-xx-1",
  "url": "/testers/xxxxx-xx-1",
  "collection": [
    {
      "text": "How hot will it be today?",
      "top_class": "temperature",
      "classes": [
        {
          "class_name": "temperature",
          "confidence": 0.993
        },
        {
          "class_name": "conditions",
          "confidence": 0.006
        }
      ]
    },
    {
      "text": "Is it hot outside?",
      "top_class": "temperature",
      "classes": [
        {
          "class_name": "temperature",
          "confidence": 1.0
        },
        {
          "class_name": "conditions",
          "confidence": 0.0
        }
      ]
    }
  ]
}

电流输出

代码和不需要的输出

我试过json_normalize,但是它给出了重复。

如何将此 Jason 文件转换为 Pandas DataFrame?

每个集合的记录应该扩大,而不是很长。

【问题讨论】:

    标签: python json pandas dataframe normalize


    【解决方案1】:

    如果 json_normalize() 不适用于您的 json 结构,您可以使用自定义逻辑对其进行解析。这是一个例子:

    # define dictionary with desired structure
    d = {
         'text': [],
         'top_class': [],
         'temperature': [],
         'confidence': [] 
    }
    
    # load json
    data = json.loads(response)
    
    # iterate over collection and extract elements needed
    for el in data['collection']:
        d['text'].append(el['text'])
        d['top_class'].append(el['top_class'])
        d['temperature'].append([e['confidence'] for e in el['classes'] if e['class_name'] == 'temperature'][0])
        d['confidence'].append([e['confidence'] for e in el['classes'] if e['class_name'] == 'conditions'][0])
        
    df = pd.DataFrame(d)
    
    df.head()
    

    输出:

    【讨论】:

      【解决方案2】:
      df = pd.DataFrame([flatten_json(x) for x in response['collection']])
      
      # display(df)
                              text    top_class classes_0_class_name  classes_0_confidence classes_1_class_name  classes_1_confidence
      0  How hot will it be today?  temperature          temperature                 0.993           conditions                 0.006
      1         Is it hot outside?  temperature          temperature                 1.000           conditions                 0.000
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-12
        • 2020-12-28
        • 2021-03-15
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 2012-07-05
        • 2021-07-17
        相关资源
        最近更新 更多