Home > Mobile >  creating a list of dataframes from list of lists of dataframes in python
creating a list of dataframes from list of lists of dataframes in python

Time:12-09

I have a list of list of dataframes

list = {[df1],[df1,df2],[df1,df2,df3]} that I want to concatenate the dataframes in one list to one dataframe, ultimately resulting in a list of dataframes.

what I want:

list1 = [df_a, df_b, df_c]

where

df_a = df1, 
df_b = df1   df2, 
df_c = df1   df2  df3

I tried

list1=[]
for n in list:
    list1.append(pd.concat([list[n]]))

but it raised error TypeError: list indices must be integers or slices, not list

how can I achieve list1?

CodePudding user response:

I have created the 3 sample pandas data-frames for your questions solution

import pandas as pd

df1=pd.DataFrame({'numbers': [1, 2, 3], 'colors': ['red', 'white', 'blue']})
df2=pd.DataFrame({'numbers': [4, 5, 6], 'colors': ['Orange', 'Green', 'White']})
df3=pd.DataFrame({'numbers': [7, 8, 9], 'colors': ['black', 'yellow', 'Purple']})

# Define the list of lists of dataframes
list_of_lists = [[df1], [df1, df2], [df1, df2, df3]]
# Initialize an empty list to hold the concatenated dataframes
concatenated_list = []

# Loop through the list of lists of dataframes
for df_list in list_of_lists:
   concatenated_df = pd.concat(df_list)
   concatenated_list.append(concatenated_df)
# Print the list of concatenated dataframes
print(concatenated_list)

In case if it solves your problem please accept this as an Answer.

CodePudding user response:

You can use the pandas.concat() function for this purpose

df = pd.concat([df1, df2], axis=1)
  • Related