熊猫-TypeError:元组索引必须是整数或切片,而不是str

时间:2019-07-14 23:54:30

标签: python pandas

我正在尝试在熊猫中设置一个简单的DataFrame,该熊猫从JSON文件(特别是从Alpha Vantage)导入数据。我正在寻求解决该功能扇区性能,因为Microsoft可以正常运行而不会出现错误。 部门的JSON文件: https://www.alphavantage.co/query?function=SECTOR&apikey=demo

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

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

仅在具有扇区性能而不是Microsoft时才收到此错误,但是两个功能非常相似。

1 个答案:

答案 0 :(得分:0)

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

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