【问题标题】:Create combined data frame from JSON using pandas使用 pandas 从 JSON 创建组合数据框
【发布时间】:2018-08-03 02:25:30
【问题描述】:

我正在从 Alpha_Vantage 导入 JSON 格式的数据:

{
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "MSFT",
        "3. Last Refreshed": "2018-08-02",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2018-08-02": {
            "1. open": "105.4000",
            "2. high": "108.0900",
            "3. low": "104.8400",
            "4. close": "107.5700",
            "5. volume": "26080662"
        },...

我想从不同的代码中提取不同的数据并将它们组合起来,将日期作为索引和每个代码的“4.close”列。到目前为止,这就是我所拥有的:

from alpha_vantage.timeseries import TimeSeries
from pprint import pprint

tickers = ['KHC', 'TSLA']
for t in range(len(tickers)):
  ts = TimeSeries(key='my_api_key', output_format='pandas')
   data, meta_data = ts.get_daily(symbol= tickers[t], 
                                    outputsize='compact')
  accu = data['4. close'].head()
  data_merged = data.merge(accu.to_frame(), how='left'\ 
                            , left_on='date' 
                            , right_index=True)

  pprint(data_merged.head)

目前,left_on 中的“日期”存在键错误,即使在打印单个代码时该键出现在列中。绑定另一个键只会弄乱数据。任何的想法?另外,如何在每列的顶部打印代码名称?

【问题讨论】:

  • 'date' 可能是索引,而不是列。 accu.to_frame().head() 显示什么?
  • @DYZ '日期' 和 '4.关闭每个股票代码,但由于我无法合并它而分开。
  • 所以,data 是您的数据框。在您的代码片段中,您尝试将其与自己的头部合并,这是没有意义的。您想要的是合并在每次循环迭代中获得的数据帧。

标签: python json python-3.x pandas dataframe


【解决方案1】:

你需要将获得的“4.close”系列收集到一个字典中,然后从字典中构建一个DataFrame:

tickers = ['KHC', 'TSLA']
ts = TimeSeries(key='my_api_key', output_format='pandas')

closes_4 = {} # Start with an empty dictionary

for t in tickers:
    data, _ = ts.get_daily(symbol=t, outputsize='compact')
    closes_4[t] = data['4. close'] # Add a series to the dict

close_df = pd.DataFrame(closes_4)

【讨论】:

    猜你喜欢
    • 2014-01-05
    • 2020-12-22
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 2021-01-09
    • 2019-10-22
    相关资源
    最近更新 更多