【问题标题】:Pandas - TypeError: tuple indices must be integers or slices, not strPandas - TypeError:元组索引必须是整数或切片,而不是 str
【发布时间】:2019-11-23 16:45:31
【问题描述】:

我正在尝试在 pandas 中设置一个简单的 DataFrame,它从 JSON 文件(特别是 Alpha Vantage)导入数据。我正在寻找修复功能部门性能,因为微软运行良好而没有错误。 扇区的 JSON 文件: https://www.alphavantage.co/query?function=SECTOR&apikey=demo

我是 pandas 的新手,所以我尝试更改了几行代码,但没有成功。我确定我缺少一些基本但找不到的东西。

import requests
import pandas as pd
import datetime
api_key = open("APIkey.txt", "r").read()

def microsoft():
    data = requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=' + api_key)
    data = data.json()
    data = data['Time Series (5min)']
    df = pd.DataFrame(columns = ['date', 'open', 'high', 'low', 'close', 'volume'])
    for d,p in data.items():
        date = datetime.datetime.strptime(d,'%Y-%m-%d %H:%M:%S')
        data_row = [date, float(p['1. open']), float(p['2. high']), float(p['3. low']), float(p['4. close']), int(p['5. volume'])]
        df.loc[-1, :] = data_row
        df.index = df.index + 1
    data = df.sort_values('date')
    df["diff"] = df["close"].diff(-1)
    df["range"] = df["high"] - df["low"]
    print(df)

def sectorperformance():
    data = requests.get("https://www.alphavantage.co/query?function=SECTOR&apikey=" + api_key)
    data = data.json()
    data = data['Rank B: 1 Day Performance']
    print(data)
    df = pd.DataFrame(columns = ['Industrials', 'Consumer Discretionary', 'Materials', 'Information Technology', 'Communication Services', 'Financials', 'Energy', 'Consumer Staples', 'Real Estate', 'Utilities', 'Health Care'])
    for p in data.items():
        data_row = [float(p['Industrials']), float(p['Consumer Discretionary']), float(p['Materials']), float(p['Information Technology']), float(p['Communication Services']), float(p['Financials']), float(p['Energy']), float(p['Consumer Staples']), float(p['Real Estate']), float(p['Utilities']), float(p['Health Care'])]
        df.loc[-1, :] = data_row
        df.index = df.index + 1
    print(df)

sectorperformance()


TypeError: tuple indices must be integers or slices, not str

这个错误只在sectorperformance而不是microsoft收到,但两个函数非常相似。

【问题讨论】:

  • 使用跟踪显示完整错误,并记下您进行了哪些调试以及将问题缩小到的位置。
  • data.items() 为您提供了一个元组,您可以将其保存到扇区性能中的 p 中,然后使用一些字符串对 p 进行索引。另外,其他人所说的应该如何改进您的帖子是完全正确的

标签: python pandas


【解决方案1】:

如果没有完整的堆栈跟踪很难说,但我会继续猜测 data.items() 在扇区性能中迭代时会产生元组,而您期望它是字典。

您收到的数据可能与您预期的格式不同。

【讨论】:

    猜你喜欢
    • 2017-03-11
    • 2018-12-29
    • 2021-01-18
    • 2018-03-12
    • 1970-01-01
    • 2015-12-09
    • 2019-02-05
    • 2021-11-28
    相关资源
    最近更新 更多