这是我的代码。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import quandl
start = pd.to_datetime('2012-01-01')
end = pd.to_datetime('2017-01-01')
aapl = quandl.get('WIKI/aapl.11', start_date = start, end_date= end )
csco = quandl.get('WIKI/csco.11', start_date = start, end_date= end )
ibm = quandl.get('WIKI/ibm.11', start_date = start, end_date= end )
amzn = quandl.get('WIKI/amzn.11', start_date = start, end_date= end )
这将创建4个数据帧。我希望能够通过使用for循环来实现。
这就是我想像的for循环。
for i in [aapl,csco,ibm,amzn]:
a = 'WIKI/'+ i + '.11'
i = quandl.get(a, start_date=start, end_date=end)
我希望能够在循环中将数据帧的名称作为字符串引用,以执行其他需要将数据帧的名称作为字符串的功能。
任何人都可以帮助我解决这个问题,或者提出另一种可以达到相同结果的方法。我希望能够以可扩展到100次循环迭代的方式来做到这一点。
谢谢您的帮助。
答案 0 :(得分:0)
inames = ['aapl', 'csco', 'ibm', 'amzn']
data = {name: quandl.get('WIKI/'+ name + '.11', start_date=start, end_date=end) for name in inames}
答案 1 :(得分:0)
您快到了!您所要做的就是将列表元素括在字符串中。
您现在正在做什么:
a = 'WIKI/'+ i + '.11' # Where i is an object, probably a pointer/instance
您需要做什么:
a = 'WIKI/'+ i + '.11' # Where i is a good-old-happy string
因此,您的代码中的代码应类似于:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import quandl
start = pd.to_datetime('2012-01-01')
end = pd.to_datetime('2017-01-01')
# You have to add Strings to calculate i (But, you are adding objects)
L = ["aap1", "csco", "ibm", "amzn"]
L_i = []
for i in L:
a = 'WIKI/'+ i + '.11'
i = quandl.get(a, start_date=start, end_date=end)
# Then do whatever you want with the i-s : L_i.append(i)
答案 2 :(得分:0)
等同于GB的答案,但如果您不熟悉字典,则无需理解字典。
import pandas as pd
import quandl
start = pd.to_datetime('2012-01-01')
end = pd.to_datetime('2017-01-01')
data = {}
for key in ['aapl', 'csco', 'ibm', 'amzn']:
name = 'WIKI/'+ key + '.11'
data[key] = quandl.get(name, start_date=start, end_date=end)
# Then you can use it like
data['aapl'].DoSomething()