【问题标题】:Json convert DataFrameJson 转换 DataFrame
【发布时间】:2021-04-20 07:08:38
【问题描述】:

我有一个 Jston dict 类型数据,如下所示:

{'statusCode': 200,
 'body': {'lambdaData': {'20210302': {'004565': 33010.29666478985,
    '002780': 119.79041526659631,
    '043200': 494.0269995476475, 
    '273140': 41.252622294271745,
    ...},
   'returnType': 'PAYLOAD'},
  'returnType': 'PAYLOAD'}}

我想改变喜欢(熊猫数据框):

yyyymmdd stock_code  rate
20210302 004565      33010.29666478985
20210302 002780      119.79041526659631
20210303 004565      32010.29666478985
20210302 002780      219.79041526659631

谢谢

【问题讨论】:

  • 你能分享一下你到目前为止的尝试吗?

标签: python json dataframe


【解决方案1】:

考虑到您在 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便于理解。

【讨论】:

    猜你喜欢
    • 2017-04-13
    • 2021-03-29
    • 1970-01-01
    • 2019-07-12
    • 2018-05-17
    • 1970-01-01
    • 2022-11-17
    • 2022-11-16
    相关资源
    最近更新 更多