【问题标题】:nested dictionary in list to dataframe python列表中的嵌套字典到数据框python
【发布时间】:2021-06-11 07:22:55
【问题描述】:

有一个来自 api 的 json 输入:

{
  "api_info": {
    "status": "healthy"
  },
  "items": [
    {
      "timestamp": "time", 
      "stock_data": [
        {
          "ticker": "string",
          "industry": "string",
          "Description": "string"
        }
      ]
     "ISIN":xxx,
     "update_datetime": "time"
    }
  ]
}

已经开始运行

apiRawData = requests.get(url).json()['items']

然后运行 ​​json_normalize 方法:

apiExtractedData = pd.json_normalize(apiRawData,'stock_data',errors='ignore')

这是 stock_data 仍包含在列表中的初始输出。 stock_data ISIN update_datetime 0 [{'description': 'zzz', 'industry': 'C', 'ticker...xxx time

stock_data ISIN update_datetime
0 [{'description': 'zzz', 'industry': 'C', 'ticker...] 123 time

我想要实现的是显示标题和相应行的数据框:

description industry ticker ISIN update_datetime
0 'zzz' 'C' xxx 123 time

如果已经回答了现有问题,请指导我:) 干杯。

【问题讨论】:

    标签: python-3.x dataframe json-normalize


    【解决方案1】:

    我认为您可以使用以下代码简单地将现有数据框转换为预期的数据框:

    apiExtractedData['description'] = apiExtractedData['stock_data'].apply(lambda x: x[0]['description'])
    apiExtractedData['industry'] = apiExtractedData['stock_data'].apply(lambda x: x[0]['industry'])
    apiExtractedData['ticker'] = apiExtractedData['stock_data'].apply(lambda x: x[0]['ticker'])
    

    然后删除您的 stock_data 列:

    apiExtractedData = apiExtractedData.drop(['stock_data'], axis = 1)
    

    【讨论】:

    • @BrandonWong 嗨,如果您觉得答案有帮助,请点击答案左侧的按钮接受它:)
    • 哈哈。 @Divyessh,声望低于 15 人的投票将被记录,但不要更改公开显示的帖子得分。
    猜你喜欢
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多