python-3.x - nested dictionary in list to dataframe python
问题描述
Have a json input from api:
{
"api_info": {
"status": "healthy"
},
"items": [
{
"timestamp": "time",
"stock_data": [
{
"ticker": "string",
"industry": "string",
"Description": "string"
}
]
"ISIN":xxx,
"update_datetime": "time"
}
]
}
have initially run
apiRawData = requests.get(url).json()['items']
then ran the json_normalize method:
apiExtractedData = pd.json_normalize(apiRawData,'stock_data',errors='ignore')
Here is the initial output where the stock_data is still contained within a list. 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 |
What i would like to achieve is a dataframe showing the headers and the corresponding rows:
description | industry | ticker | ISIN | update_datetime | |
---|---|---|---|---|---|
0 | 'zzz' | 'C' | xxx | 123 | time |
Do direct me if there is already an existing question answered :) cheers.
解决方案
I think you can simply convert your existing data frame into your expected one by using below code:
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'])
And then just delete your stock_data column:
apiExtractedData = apiExtractedData.drop(['stock_data'], axis = 1)
推荐阅读
- c# - 返回字符串而不是整数
- python - Django orm - 如何在不同日期的查询中获取不同的字段项
- java - 相当于没有弹出窗口和一个可选选项的 Android 单选按钮?
- bash - 为什么 bash 子外壳中的 EXIT 陷阱并不总是被调用?
- python - TypeError:预期的字符串或类似字节
- r - 使用错误的含义。dplyr 函数中的简写
- c++ - 如何使用 Qt3D 设置多个视口而无需使用 QML
- ios - Xcode 10 不显示图像并删除了 Xcode 9 上的自动布局约束
- c - 在 x86 程序集中将浮点文字转换为 int 表示?
- swift - 对成员 'tableView(_:didSelectRowAt:)' 的模糊引用(Swift)