Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Store multiple dataframe in list

I have a loop that read Excel sheets in a document. I want to store them all in a list:

  DF_list= list()

  for sheet in sheets:
     df= pd.read_excel(...)
     DF_list = DF_list.append(df)

If I type:

[df df df df]

it works.

Sorry I have a Matlab background and not very used to Python, but I like it. Thanks.

like image 745
Dr.Will Avatar asked Jan 11 '18 16:01

Dr.Will


People also ask

Can I store multiple Dataframes in a list?

Actually there's no need to define new list to store bunch of dataframes. The pandas. ExcelFile function applied on excel file with multiple sheets returns ExcelFile object which is a collection that can catch hold bunch of dataframes together. Hope the below code helps.

How do you add multiple Dataframes to a list?

Method 1: Using merge() First create more than two data frames, so that we could able to merge them. Now, use merge() function along with the required parameters. Now, pass this merged dataframe to as. list() to convert it into a list.

How do I store multiple Dataframes in one variable python?

Method 1: Using concat() method This method will stack the rows of the pandas dataframes in the order they give. Parameters: dataframes are the input dataframes to be stacked. ignore_index is used to ignore the index values of the input dataframes.

How do you add Dataframes to a list in Python?

By using df. loc[index]=list you can append a list as a row to the DataFrame at a specified Index, In order to add at the end get the index of the last record using len(df) function. The below example adds the list ["Hyperion",27000,"60days",2000] to the end of the pandas DataFrame.


1 Answers

.append() modifies a list and returns None. You override DF_list with None in your first loop and the append will fail in the second loop.

Therefore:

DF_list = list()

for sheet in sheets:
    DF_list.append(pd.read_excel(...))

Or use a list comprehension:

DF_list = [pd.read_excel(...) for sheet in sheets] 
like image 142
Mike Müller Avatar answered Oct 06 '22 00:10

Mike Müller