简体   繁体   中英

Creating Multiple Pandas Data Frames in a loop

Trying to create a pandas data frame for each stock ticker in a list

My Code:

for ticker in stock_tickers:
   
     data = pd.read_csv(f'{ticker}_{get_date()}.csv')

it will only create one pandas data frame for the last stock ticker... is there anyway for this to be done all of them?

You end up with only one data set because the data variable gets overwritten on every step of the loop.

You could store your data in a dictionary (assuming here that ticker is a string):

data = {}

for ticker in stock_tickers:
    data[ticker] = pd.read_csv(f'{ticker}_{get_date()}.csv')

More compact version using a dict comprehension:

data = {ticker: pd.read_csv(f'{ticker}_{get_date()}.csv')
        for ticker in stock_tickers}

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