【发布时间】: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 进行索引。另外,其他人所说的应该如何改进您的帖子是完全正确的