0

I split an existing data frame into smaller data frames of sizes of 100. In a next step, I want to name all of those data frames so that all data frames have specific names:

This should look the following way: df1 should have the first 100 entries, followed by df2 with 101-201 and so on, how can I do that?

I thought of something like:

for i in range(0,len(df_total)):
   paste("df",i,sep="") = df_total[i]

Unfortunately I always get the following error message: cannot assign to function call

Thank you for your help!

  • Can you explain what you are trying to with `paste("df",i,sep="") = df_total[i]`? – ThePyGuy Aug 18 '21 at 14:51
  • df_total[1] is one data frame with 100 entries, I want it to be named df1, df_total[2] is another data frame with 100 entries and I want it to be named df2, and so on – Data_Science_110 Aug 18 '21 at 14:53
  • So, you just want to create individual variables out of the list of dataframes? – ThePyGuy Aug 18 '21 at 14:55
  • Yes, each data frame should have an individual name – Data_Science_110 Aug 18 '21 at 14:56
  • 1
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – ThePyGuy Aug 18 '21 at 14:56
  • I looked through it, but I still cannot solve my problem.. – Data_Science_110 Aug 18 '21 at 15:10
  • Any time you find yourself wanting a series of multiple variables like `df1`, `df2`, etc, you probably want to use a `list` or `dict` instead. I suggest you read through the thread that @ThePyGuy posted again. – 0x5453 Aug 18 '21 at 15:22

1 Answers1

1

So, df_total is the list of dataframes right? Just iterate it using enumerate, then assign the global variable using globals:

for idx,df in enumerate(df_total, 1):
    globals()[f'df{idx}'] = df

Please be noted that creating variable like this is not a recommended way, if you need to have reference by name, you can always use a dictionary:

dfs = {}
for idx,df in enumerate(df_total, 1):
    dfs[f'df{idx}'] = df

You can later access the dataframes in dictionaries like dfs['df1'], dfs['df2'], ... so on.

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45