是否有一种方法可以使用“ for循环”或类似的方式来遍历代码,以创建多个带有熊猫的DataFrame(可以分配给单独的变量),而不是对两个DataFrame进行硬编码?
如果我添加新的代码,则继续对其进行硬编码并不是有效的方法。
import pandas_datareader as pdr
from datetime import datetime
Equity_Tickers = ["FB", "MSFT"]
start = datetime(2018, 9, 15)
end = datetime.today().date()
# First DataFrame
data = pdr.DataReader(Equity_Tickers[0], 'yahoo', start, end)
df = data[['Adj Close']]
# Second DataFrame
data = pdr.DataReader(Equity_Tickers[1], 'yahoo', start, end)
df1 = data[['Adj Close']]
答案 0 :(得分:1)
您当然可以使用变量,而不是对代码进行硬编码:
ticker = Equity_Tickers[0] # FB
data = pdr.DataReader(ticker, 'yahoo', start, end)
要创建循环,可以执行以下操作:
for ticker in Equity_Tickers:
data = pdr.DataReader(ticker, 'yahoo', start, end)
df = data[['Adj Close']]
棘手的事情是在循环的每次迭代中存储df
变量,而不是覆盖它。一种解决方案是将每个DataFrame存储在列表或字典中。
frames = []
for ticker in Equity_Tickers:
data = pdr.DataReader(ticker, 'yahoo', start, end)
frames.append(data[['Adj Close']])
# eg, use frames[0] to access first ticker's DataFrame
OR
frames = {}
for ticker in Equity_Tickers:
data = pdr.DataReader(ticker, 'yahoo', start, end)
frames[ticker] = data[['Adj Close']]
# eg, use frames['FB'] to access FB ticker's DataFrame
如果您真的很喜欢,您还可以使用list comprehension /词典理解来一行完成此操作:
# list comprehension
frames = [pdr.DataReader(t, 'yahoo', start, end)[['Adj Close']] for t in Equity_Tickers]
# dict comprehension
frames = {t: pdr.DataReader(t, 'yahoo', start, end)[['Adj Close']] for t in Equity_Tickers}
附加说明:您还可以考虑将帧组合成一个大的DataFrame,也许是tidy-style DataFrame,其中“ ticker”是每一行的字段。