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

3
  • 1
    Possible duplicate of How do I create a variable number of variables? Commented Nov 25, 2019 at 14:57
  • 2
    You can also look at this answer - 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. Commented Nov 25, 2019 at 15:02
  • I'd recommend you use a directory structure instead of creating variables. Commented Nov 25, 2019 at 15:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
It's worth noting that the documentation for 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.
@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 ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.