0

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?

4
  • Create a list outside of the for loop and then .append() the newly created pandas dataframe Commented Nov 4, 2021 at 23:31
  • Can you give more details. You need one dataframe for all your csv files or you need a list of dataframes? Commented Nov 4, 2021 at 23:33
  • It's not "only creating one pandas data frame for the last stock ticker", each iteration creates and overwrites each ticker's dataframe! When the loop finished, data just happens to be the last dataframe, the only one that didn't get overwritten. Really you need to read and pd.concat () multiple dataframes, with an extra column for 'ticker'. Dataframes don't magically concatenate themselves, you have to do that explicitly. Commented Nov 5, 2021 at 0:03
  • Duplicate of How to append/concat pandas dataframes of stock prices into one large dataframe. This question gets reasked once a month, please see existing duplicates. Commented Nov 5, 2021 at 0:15

1 Answer 1

2

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.