pandas -如何将数据从嵌套字典加载到数据框? [英] pandas - How to load data from nested dictionary into dataframe?

查看:59
本文介绍了 pandas -如何将数据从嵌套字典加载到数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个具有股票收盘价的数据框,并找到了一个免费的api,该api以嵌套字典的形式返回与数据相关的JSON数据,如下所示:

I'm tryping to create a dataframe with closingprices for stocks and have found a free api that returns JSON-data in the form of nested dicts with the data, looking like this:

{'name': 'AAPL',
 'history': 
           {'2019-01-04': 
                  {'open': '144.53',
                   'close': '148.26',
                   'high': '148.55',
                   'low': '143.80',
                   'volume': '58607070'},
           '2019-01-03': 
                   {'open': '143.98',
                    'close': '142.19',
                    'high': '145.72',
                    'low': '142.00',
                    'volume': '91312195'},
          '2019-01-02': 
                  {'open': '154.89',
                   'close': '157.92',
                   'high': '158.85',
                   'low': '154.23',
                   'volume': '37039737'
}}}

因为我想要的键关闭"嵌套在历史记录"中,并且每个特定的日期我都很难提取它并将其放入数据框中.

Since my desired key 'close' is nested in 'history' and each specific date I'm having a hard time extracting it and putting it in a dataframe.

在这种情况下如何前进/逻辑化?我试过用datetime生成日期列表,但没有成功.您有什么建议或建议吗?

What is the way to go/logic behind this type of situation? I have tried generating list of dates with datetime with no success. Do you have any suggestions or readings?

当前代码,显然不能正常工作

CURRENT CODE, not working obviously

def make_request():
    '''Makes a request to the API that returns a JSON-response '''
    r = requests.get(url)
    sample = json.loads(r.text)
    return sample


def check_keys(data):
    '''Checks the keys in the JSON-response'''
    print(data.keys())


def check_values(data):
    '''Checks the values in the JSON-respose'''
    print(data.values())


def get_values(data):
    '''Gets the date for each day in the sample and stores it in a list'''
     for v in data.get('history'):
        values = v
        return v


def get_closeprice(data, values):
    '''Uses the dates from get_values() to iterate through the sample and get the
    closing price for each date in the sample'''
    for date in values:
        data.get('history').get(values).get('close')
        return value

推荐答案

您不需要知道存在哪个密钥即可访问它.您可以仅迭代字典中的所有键.

You don't need to know which key is present to access it. You can just iterate over all the keys in the dictionary.

d = <your dict>
retval = {}

for k,v in d['history'].items():
    retval[k] = v['close']

print(retval)

这篇关于 pandas -如何将数据从嵌套字典加载到数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆