【问题标题】:Select a JSON array based on name value and change the array into a Dataframe根据名称值选择一个 JSON 数组并将该数组更改为 Dataframe
【发布时间】:2023-02-08 02:38:08
【问题描述】:

是否可以选择一个特定的 JSON 数组(对应于下面的名称“contents”)并将该数组更改为 pandas 数据框?我的json如下

html_sample3 =    """{
         "orderID": 12345,
          "shopperName": "John Smith",
          "shopperEmail": "johnsmith@example.com",
          "contents": [
            {
              "productID": 34,
              "productName": "SuperWidget",
              "quantity": 1
            },
            {
              "productID": 56,
              "productName": "WonderWidget",
              "quantity": 3
            }
          ],
          "orderCompleted": true
        }"""

我写的代码非常稀疏,难倒了这一点。

from bs4 import BeautifulSoup
import pandas as pd

soup1 = BeautifulSoup(html_sample3)

我想要的数据框如下所示。

【问题讨论】:

    标签: python json pandas dataframe beautifulsoup


    【解决方案1】:

    根据提供的信息,您可以使用 json.loads() 转换字符串并使用 pandas.json_normalize()

    import json
    import pandas as pd
    
    json_sample =    json.loads("""{
             "orderID": 12345,
              "shopperName": "John Smith",
              "shopperEmail": "johnsmith@example.com",
              "contents": [
                {
                  "productID": 34,
                  "productName": "SuperWidget",
                  "quantity": 1
                },
                {
                  "productID": 56,
                  "productName": "WonderWidget",
                  "quantity": 3
                }
              ],
              "orderCompleted": true
            }""")
    
    
    pd.json_normalize(json_sample, record_path='contents')
    

    输出

    productID productName quantity
    0 34 SuperWidget 1
    1 56 WonderWidget 3

    【讨论】:

      猜你喜欢
      • 2021-05-23
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多