简体   繁体   中英

Loop over list of pandas dataframes

I'm downloading stock data files from Yahoo for a list of symbols

list_of_stocks = ['AAPL', 'GOOG', 'YHOO', 'NFLX']
for symbols in list_of_stocks:
    globals()['%s' % symbols] = DataReader(symbols, 'yahoo')

Now, downloaded data frames got saved as AAPL, GOOG, YHOO and NFLX. Then, I want to pass all these dfs to a function, for example

def check(data):
    return data

My question is how to send all these dfs to check function? I tried:

for symbols in list_of_stocks:
   print(check(symbols))

It's not working for me, this loop is just sending strings (AAPL,...) not actual data frames.

You managed to declare and assign the variables, but you don't know how to access them. That makes me think the first snippet you have in the question detail is not written by you.

Because of this thought, I am going to explain what your first snippet is doing.

list_of_stocks = ['AAPL', 'GOOG', 'YHOO', 'NFLX']
for symbols in list_of_stocks:
    globals()['%s' % symbols] = DataReader(symbols, 'yahoo')

Ok, you called the globals() function, which gives you a reference to the dictionary at which the interpreter looks when it tries to find global variables. Then you put in the dataframes as values, with corresponding keys symbols in string. Iterate through symbols in a for loop, and we are done.

Now, given the same list you just iterated through, how do you get values out from the dictionary again?

for symbols in list_of_stocks:
    print(check(globals()['%s' % symbols]))

The way you assigned them. Period.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM