无法读取JSON导入的Pandas DataFrame指定列问题求助
问题:KeyError异常 - 'totalRevenue'和'future_revenue'列不存在(已确认totalRevenue存在)
尝试读取从JSON导入的Pandas DataFrame时抛出KeyError,提示数据中不存在'totalRevenue'和'future_revenue'列。我已确认'totalRevenue'在原始JSON和DataFrame中都存在,但错误仍发生;针对'totalRevenue'的错误处理完全失效,且因'future_revenue'是后续要创建的字段,它的错误处理也无法正常工作。
以下是我的代码:
import requests import json import pandas as pd import numpy as np import matplotlib.pyplot as plt # 替换为你的Alpha Vantage API密钥 api_key = 'YOUR API KEY' # 获取用户输入的股票代码 ticker_symbol = input("输入公司的股票代码: ") # 获取三种财务报表 functions = ['INCOME_STATEMENT', 'BALANCE_SHEET', 'CASH_FLOW'] financial_data = {} for function in functions: # 指定数据频率 interval = 'annual' # 可选值为'quarter' # 向Alpha Vantage API发送请求获取财务数据 url = f'https://www.alphavantage.co/query?function={function}&symbol={ticker_symbol}&apikey={api_key}&interval={interval}' response = requests.get(url) # 检查响应状态码和内容,处理API请求错误 if response.status_code != 200: print("错误:API请求失败,状态码", response.status_code) print(response.content) exit() try: financial_data[function] = json.loads(response.text) except json.decoder.JSONDecodeError as e: print("错误:解析API响应的JSON数据失败") print(e) print(response.content) exit() # 将财务数据加载到Pandas DataFrame financial_data = pd.DataFrame(financial_data) # 示例费用率(费用占收入的比例) expense_ratio = 0.6 # 示例增长率 growth_rate = 0.03 # 检查数据是否包含'totalRevenue'列 if 'totalRevenue' not in financial_data.columns: print("数据中不存在'totalRevenue'列。") if 'future_revenue' not in financial_data.columns: print("数据中不存在'future_revenue'列。") else: # 基于固定费用率创建未来费用列 financial_data['future_expenses'] = financial_data['future_revenue'] * expense_ratio else: # 基于固定增长率创建未来收入列 financial_data['future_revenue'] = financial_data['totalRevenue'].iloc[-1] * (1 + growth_rate)**(range(1, len(financial_data) + 1)) # 基于固定费用率创建未来费用列 financial_data['future_expenses'] = financial_data['future_revenue'] * expense_ratio # 假设折现率为10% discount_rate = 0.1
内容的提问来源于stack exchange,提问作者BonesOnFire
相关产品推荐
相关产品推荐

