0

I have a list of numbers

ex_list = [0, 3, 5] The amount of numbers is dynamic(usually).

I have a data frame variable:

ex_df = pd.read_csv(*some df*)

Is it possible to create a copy of this ex_df for each of the variables in ex_list and name it:

ex_df_0

ex_df_3

ex_df_5

Each of those will be a copy of ex_df

Toby Djelyinski
  • 128
  • 1
  • 11
  • 1
    Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – pault Nov 25 '19 at 14:57
  • 2
    You can also look at this answer - https://stackoverflow.com/a/40974699/6590393. Loop over `ex_list` and store data frames in a dictionary, as suggested in the answer shared by @paul too. Dynamic variable names is not a good practice. – Rachayita Giri Nov 25 '19 at 15:02
  • I'd recommend you use a directory structure instead of creating variables. – Scott Boston Nov 25 '19 at 15:07

1 Answers1

1

A simple way of doing this would be to use locals() function -

Code

ex_list = [0, 3, 5]
ex_df = pd.read_csv(*some df*)

for i in ex_list:
    locals()['ex_df_'+str(i)] = ex_df.copy()

This will create 3 dataframes, ex_df_0, ex_df_3, ex_df_5 which will all be copies of dataframe ex_df.

Gary
  • 909
  • 8
  • 20
  • 2
    looks like a solution. Thanks. I will try to think of a different approach to my problem as per @RachayitaGiri 's suggestion that it is bad practice for dynamic variable creation. – Toby Djelyinski Nov 25 '19 at 15:07
  • 1
    It's worth noting that the documentation for [`locals()`](https://docs.python.org/3/library/functions.html#locals) does come with a note that says: *The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.* – Jon Clements Nov 25 '19 at 15:15
  • @JonClements I do not understand that statement, contents of `locals()` will get modified each time we define a new df anyway. Could you please elaborate a bit more ? – Gary Nov 25 '19 at 21:01