gpt4 book ai didi

python - pandas - 如何将嵌套字典中的数据加载到数据框中?

转载 作者:太空宇宙 更新时间:2023-11-04 08:27:36 25 4
gpt4 key购买 nike

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

{'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'
}}}

由于我想要的键“关闭”嵌套在“历史”和每个特定日期中,所以我很难提取它并将其放入数据框中。

这种情况背后的方法/逻辑是什么?我曾尝试生成带有日期时间的日期列表,但没有成功。您有什么建议或读物吗?

编辑:当前代码,显然不起作用

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

最佳答案

如果您只想将其加载到数据框中:

# h = your dictionary

df = pd.DataFrame.from_dict(data=h['history'],orient='index')

cols = ['close']

df = df[cols]

# Just as an aside Quandl has been very good for free financial data to me.
#It has a paid side with premium data but I havent used it.

关于python - pandas - 如何将嵌套字典中的数据加载到数据框中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55679381/

25 4 0
文章推荐: Java:扫描仪的 next() 在 Scite 和命令提示符中的行为不同
文章推荐: javascript - 如何将 DIV 及其内容与外部 CSS 隔离
文章推荐: css -
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com