1

I am trying to read multiple csv files from a list of file paths and save them all as separate pandas dataframes.

I feel like there should be a way to do this, however I cannot find a succinct explanation.

import pandas as pd

data_list = [['df_1','filepath1.csv'],
             ['df_2','filepath2.csv'],
             ['df_3','filepath3.csv']]

for name, filepath in data_list:
    name = pd.read_csv(filepath)

I have also tried:

data_list = [[df_1,'filepath1.csv'],[df_2,'filepath2.csv'],
             [df_3,'filepath3.csv']]

for name, filepath in data_list:
    name = pd.read_csv(filepath)

I would like to be able to call each dataframe by its assigned name.

Ex):

df_1.head()

3 Answers 3

1
df_dct = {name:pd.read_csv(filepath) for name, filepath in data_list}

would create a dictionary of DataFrames. This may help you organize your data.

You may also want to look into glob.glob to create your list of files. For example, to get all CSV files in a directory:

file_paths = glob.glob(my_file_dir+"/*.csv")
Sign up to request clarification or add additional context in comments.

Comments

0

I recommend you numpy. Read the csv files with numpy.

from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')

You will get nd-array's. After that you can include them into pandas.

Comments

0

You can make sure of dictionary for this...

import pandas as pd
data_list = ['filepath1.csv', 'filepath2.csv', 'filepath3.csv']
d = {}
for _, i in enumerate(data_list):
    file_name = "df" + str(_)
    d[file_name] = pd.read_csv(filepath)

Here d is the dictionary which contains all your dataframes.

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.