Home > Net >  Separate a list of data frames into multiple data frames
Separate a list of data frames into multiple data frames

Time:12-02

I have a list of data frames that was created using a user-defined function -

a = list(map(test, cat_feature_names))

where

cat_feature_names = ['Brand', 'Variety', 'Style', 'Country', 'Stars', 'Top Ten']

and the function is this

def test(col):
    vc = df[col].value_counts().rename_axis('unique_values').reset_index(name='counts')
    vc['feature'] = col
    vc['frequency']=round((vc['counts']/(vc['counts'].sum())*100),2)
    vc = vc[['feature','unique_values','counts','frequency']]
    no_of_unique = len(vc)
    return vc  

Now, I need to separate the contents of "a" into multiple data frames that are of separate size and shape. I need to do this dynamically. All I am able to do now is extract one data frame at a time, like so

a[0]

A for loop would not work because there might be a very large number of data frames in the list "a".

Please help.

CodePudding user response:

IIUC, you're separating a df in multiple dataframes, giving a column name as parameter to your mapping function test.

One solution might be to store you dataframes in a dictionary, using the column name as key:

df_dict = dict(zip(cat_feature_names, map(test, cat_feature_names)))

You can then access each dataframe with df_dict[col_name].

CodePudding user response:

Following for loop will break your list into multiple dataframes. globals() will be used to to name it like df_0, df_1 and so on..

for i in range(len(your_list)):
    globals()[f"df_{i}"] = your_list[i]
  • Related