数据框列表中的嵌套字典 python

nested dictionary in list to dataframe python

从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', '代码...xxx 时间

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

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

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

如果已有问题已回答,请直接告诉我 :) 干杯。

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

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)