John
John

Reputation: 1

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?

Upvotes: 0

Views: 97

Answers (1)

Antimon
Antimon

Reputation: 702

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}

Upvotes: 2

Related Questions