Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read multiple csvs into multiple dataframes in Pandas

Is there a way to read multiple csv files into Pandas through a loop and define them as such?

for i in ['a', 'b', 'c', 'd']:
    csv_(i) = pd.read_csv('C:/test_{}.csv'.format(i))

I see multiple questions about reading and appending multiple csvs into a single dataframe. Not the other way around.

like image 924
cptpython Avatar asked Mar 21 '17 17:03

cptpython


People also ask

Can Pandas read multiple CSV files?

Sometimes you may need to read or import multiple CSV files from a folder or from a list of files and convert them into pandas DataFrame. You can do this by reading each CSV file into DataFrame and appending or concatenating the DataFrames to create a single DataFrame with data from all files.

How do I read multiple CSV files from a directory in Python?

Code explanation Here, the glob module helps extract file directory (path + file name with extension), Lines 10–13: We create a list type object dataFrames to keep every csv as a DataFrame at each index of that list. Line 15: We call pd. concat() method to merge each DataFrame in the list by columns, that is, axis=1 .

How do I read multiple CSV files?

In order to read multiple CSV files or all files from a folder in R, use data. table package. data. table is a third-party library hence, in order to use data.


1 Answers

You can use dict comprehension for dict of DataFrames:

dfs = {i: pd.read_csv('C:/test_{}.csv'.format(i)) for i in ['a', 'b', 'c', 'd']}

print (dfs['a'])
like image 119
jezrael Avatar answered Oct 14 '22 05:10

jezrael