考虑到您在 Jsons 中获取输入,即 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
所有代码行都有cmets便于理解。