Home > Enterprise >  how to use for loop to split dataframe (list in list) and assign new name
how to use for loop to split dataframe (list in list) and assign new name

Time:02-19

This is the data I am working with: df = [[1,2,3], [2,3,4], [5,6,7]]

I want to make sure I get a new name for each df[1] and df[2] etc so that I can use it later in my codes.

I tried using the following code: `for i in range(len(df)): df_"{}".format(i) = df[i]

Obviously I am getting error for trying to declare dataframe like that.

How best can I achieve this? of splitting list in list into seperate dataframes using for loop?

Note: I am newbie to python hence if I missed anything obvious please help me point that out.

CodePudding user response:

Use:

dfps = [[1,2,3], [2,3,4], [5,6,7]]
dic_of_dfs = {}
for i, row in enumerate(dfps):
    dic_of_dfs.update({f"df_{i}":pd.DataFrame(row)})
dic_of_dfs["df_0"]

output:

enter image description here

  • Related