Python Json转换数据帧
我有一个Jston dict类型的数据,如下所示:Python Json转换数据帧,python,json,dataframe,Python,Json,Dataframe,我有一个Jston dict类型的数据,如下所示: {'statusCode': 200, 'body': {'lambdaData': {'20210302': {'004565': 33010.29666478985, '002780': 119.79041526659631, '043200': 494.0269995476475, '273140': 41.252622294271745, ...}, 'returnType': 'PAYLOAD
{'statusCode': 200,
'body': {'lambdaData': {'20210302': {'004565': 33010.29666478985,
'002780': 119.79041526659631,
'043200': 494.0269995476475,
'273140': 41.252622294271745,
...},
'returnType': 'PAYLOAD'},
'returnType': 'PAYLOAD'}}
我想更改如下(熊猫数据帧):
谢谢你考虑到你得到的是JSON中的输入,也就是Python中的dicts 我已经编写了一些循环来进行迭代,也许有一种更优雅的方法,但为了更好地理解代码,我会用这种方法
#import
import pandas as pd
#given json/dict in a variable
testData = { 'statusCode': 200, 'body': { 'lambdaData': { '20210302': { '004565': 33010.29666478985, '002780': 119.79041526659631, '043200': 494.0269995476475, '273140': 41.252622294271745 }, 'returnType': 'PAYLOAD' }, 'returnType': 'PAYLOAD' } }
#new empty dataframe with desired column names
Mydataframe = pd.DataFrame({'yyyymmdd': [], 'stock_code': [], 'rate': []})
#iterating through input json/dict
for key, value in testData.items():
#if we found body which is again a dict
if isinstance(value, dict) and key == 'body':
#iterating through body
for subDataKey, subDataValue in value.items():
#if we found lambdaData which is again a dict
if isinstance(subDataValue, dict) and subDataKey == 'lambdaData':
#iterating through lambdaData
for lambDataKey, lambDataValue in subDataValue.items():
#checking for dicts present in the lambdaData
if isinstance(lambDataValue, dict):
#iterating through that dict
for lambDataSubKey, lambDataSubValue in lambDataValue.items():
#saving values in the df
Mydataframe = Mydataframe.append([{'yyyymmdd':lambDataKey, 'stock_code':lambDataSubKey, 'rate':lambDataSubValue}], ignore_index=True)
将给出以下df作为答案:
yyyymmdd stock_code rate
0 20210302 004565 33010.296665
1 20210302 002780 119.790415
2 20210302 043200 494.027000
3 20210302 273140 41.252622
所有代码行都有注释以供理解。您能分享您迄今为止的尝试吗?
yyyymmdd stock_code rate
0 20210302 004565 33010.296665
1 20210302 002780 119.790415
2 20210302 043200 494.027000
3 20210302 273140 41.252622