python - 赋值前引用的局部变量“df”
问题描述
我不知道该怎么做这个练习。
“您可以使用此模板来获取 DJIA 成员的调整后收盘价。
首先,您应该在线下载 DJIA 会员名单。然后你读入成员并在 main 函数中编写一个 for 循环来获取所需的数据。
提示,在 get_EOD_data 函数中使用 'tickers' 参数"
import requests
import pandas as pd
from pandas.compat import StringIO
import numpy as np
import datetime as dt
from dateutil.relativedelta import relativedelta
def get_EOD_data(api_token='5cb671b0b4a790.35526238', session = None, tickers = 'AXP', start_date = dt.datetime(2018,1,1), end_date = dt.datetime(2018,12,31)):
symbols = tickers
if session is None:
session = requests.Session()
url = 'https://eodhistoricaldata.com/api/eod/%s.US'
params = {"api_token": api_token, "from": start_date, "to": end_date}
r = session.get(url, params = params)
if r.status_code == requests.codes.ok:
# Use the parameters index_col and usecols to control which columns you want to scrape
df = pd.read_csv(StringIO(r.text), skipfooter = 1, parse_dates = [0], engine = 'python', na_values=['nan'])
df.fillna(method = 'ffill', inplace = True)
df.fillna(method = 'bfill', inplace = True)
return df
def main():
# Add parameters of the function get_EOD_data to control the data you want to scrape
df_data = get_EOD_data()
print(df_data)
if __name__ == '__main__':
main()
Traceback (most recent call last):
File "/Users/katewang/Desktop/Test/scrape_data.py", line 32, in <module>
main()
File "/Users/katewang/Desktop/Test/scrape_data.py", line 28, in main
df_data = get_EOD_data()
File "/Users/katewang/Desktop/Test/scrape_data.py", line 22, in get_EOD_data
df.fillna(method = 'ffill', inplace = True)
UnboundLocalError: local variable 'df' referenced before assignment
解决方案
在本节这里
. . . .
if r.status_code == requests.codes.ok:
# Use the parameters index_col and usecols to control which columns you want to scrape
df = pd.read_csv(StringIO(r.text), skipfooter = 1, parse_dates = [0], engine = 'python', na_values=['nan'])
df.fillna(method = 'ffill', inplace = True)
. . .
你会注意到变量的赋值df
是在一个条件语句中,它可能评估 falser.status_code
并且requests.codes.ok
不等价
推荐阅读
- java - 监听 Scoped bean 中的 spring 事件 - 如果范围处于活动状态,是否可以仅在 bean 中捕获事件?
- asp.net - ASPX 发布网站的 MS Visual Studio 2017 问题
- python - 为什么这不是字符串?
- android - 从列表中隐藏项目
- c++ - 使用 SQL VDI(虚拟设备接口)创建条带备份失败
- vue.js - 如何在 vee validate 3.0 版本中验证输入类型文件所需的验证
- ios - 每周自动更新标签
- excel - 将 xlsx 文件转换为纯 xml 格式?
- php - 我应该使用 init 系统运行官方 php-fpm 映像以避免 PID 1 问题吗?
- ansible - 强制停止 ansible 剧本