如何在 for 循环中将数据框名称引用为字符串?

How to reference a dataframe name as a string in a for loop?

这是我的代码。

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 次循环迭代的方式来做到这一点。

感谢您的帮助。

inames = ['aapl', 'csco', 'ibm', 'amzn']
data = {name: quandl.get('WIKI/'+ name + '.11', start_date=start, end_date=end) for name in inames}

你快到了!您所要做的就是将列表元素包含在字符串中。

你现在在做什么:

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)

等同于 G. B. 的答案,但没有字典理解,以防您还不熟悉它。

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()