1

I have 600 csv files that I want to read to separate data frames using pd.read.csv. I have tried the code below.

for stock in stock_list:
    df_stock = pd.read_csv("D:/Stocks/CSV/" + stock + ".csv")

I want every dataframe to be stored separately as df_the respective stock name in stock_list (for example df_pfizer, df_ICBC and so on) but instead my code is reading it into a single dataframe. The stock names are in the list stock_list.

3 Answers 3

2

Having 600 variables is not handleable, you should use a dictionary.

df_dict = {}
for stock in stock_list:
    df_dict[stock] = pd.read_csv("D:/Stocks/CSV/" + stock + ".csv")

... or:

df_dict = {stock: pd.read_csv("D:/Stocks/CSV/" + stock + ".csv") for stock in stock_list}
Sign up to request clarification or add additional context in comments.

2 Comments

what is stock_list in the dictionary comp?
@Umar.H Isn't it your list of stock names ? You can then retrieve any dataframe from the dictionary with a name, like this: df_dict["some_name"]. Please check the python dictionaries documentation.
1

You can add the dataframes into a python dict:

df_stocks = {}
for stock in stock_list:
    df_stock = pd.read_csv("D:/Stocks/CSV/" + stock + ".csv")
    df_stocks[stock] = df_stock

And to access any dataframe:

df_stocks['df_pfizer']

will return the 'df_pfizer' dataframe,

df_stocks['df_ICBC']

will return the df_stocks['df_ICBC'] dataframe, and so on.

Comments

0

you need to first create a single dataframe then seperate them based on the stockname with a dictionary comp.

from pathlib import Path
import pandas as pd

dfs = pd.concat(
                [pd.read_csv(f) for f in Path(r"D:/Stocks/CSV/").glob('*.csv')]
              )

stock_dfs = {stock : frame for stock,frame in dfs.groupby('stock_list')}

then you can call each df by its key

stock_dfs['df_pfizer']

2 Comments

Thanks Umar for such a prompt reply. But i want separate dataframes. Isnt there a way to create separate dataframes with respective names?
creating n number of variables is not recommended. use a container like a dictionary I wasn't sure if you wanted to seperated by the stock_list column or the file name. that said, the above method will handle that for you.

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.