Creating variables with dynamic names is typically a bad practice.

I think the best solution for your problem is to store your dataframes into a dictionary and dynamically generate the name of the key to access each dataframe.

import copy

dict_of_df = {}
for ym in [201511, 201612, 201710]:

    key_name = 'df_new_'+str(ym)    

    dict_of_df[key_name] = copy.deepcopy(df)

    to_change = df['YearMonth']< ym
    dict_of_df[key_name].loc[to_change, 'new_col'] = ym   

dict_of_df.keys()
Out[36]: ['df_new_201710', 'df_new_201612', 'df_new_201511']

dict_of_df
Out[37]: 
{'df_new_201511':     A    B  ID                       t  YearMonth  new_col
 0  -a    a   1 2016-12-05 07:53:35.943     201612   201612
 1   1  NaN   2 2016-12-05 07:53:35.943     201612   201612
 2   a    c   2 2016-12-05 07:53:35.943     201612   201612,
 'df_new_201612':     A    B  ID                       t  YearMonth  new_col
 0  -a    a   1 2016-12-05 07:53:35.943     201612   201612
 1   1  NaN   2 2016-12-05 07:53:35.943     201612   201612
 2   a    c   2 2016-12-05 07:53:35.943     201612   201612,
 'df_new_201710':     A    B  ID                       t  YearMonth  new_col
 0  -a    a   1 2016-12-05 07:53:35.943     201612   201710
 1   1  NaN   2 2016-12-05 07:53:35.943     201612   201710
 2   a    c   2 2016-12-05 07:53:35.943     201612   201710}

 # Extract a single dataframe
 df_2015 = dict_of_df['df_new_201511']
Answer from FLab on Stack Overflow
Top answer
1 of 2
24

Creating variables with dynamic names is typically a bad practice.

I think the best solution for your problem is to store your dataframes into a dictionary and dynamically generate the name of the key to access each dataframe.

import copy

dict_of_df = {}
for ym in [201511, 201612, 201710]:

    key_name = 'df_new_'+str(ym)    

    dict_of_df[key_name] = copy.deepcopy(df)

    to_change = df['YearMonth']< ym
    dict_of_df[key_name].loc[to_change, 'new_col'] = ym   

dict_of_df.keys()
Out[36]: ['df_new_201710', 'df_new_201612', 'df_new_201511']

dict_of_df
Out[37]: 
{'df_new_201511':     A    B  ID                       t  YearMonth  new_col
 0  -a    a   1 2016-12-05 07:53:35.943     201612   201612
 1   1  NaN   2 2016-12-05 07:53:35.943     201612   201612
 2   a    c   2 2016-12-05 07:53:35.943     201612   201612,
 'df_new_201612':     A    B  ID                       t  YearMonth  new_col
 0  -a    a   1 2016-12-05 07:53:35.943     201612   201612
 1   1  NaN   2 2016-12-05 07:53:35.943     201612   201612
 2   a    c   2 2016-12-05 07:53:35.943     201612   201612,
 'df_new_201710':     A    B  ID                       t  YearMonth  new_col
 0  -a    a   1 2016-12-05 07:53:35.943     201612   201710
 1   1  NaN   2 2016-12-05 07:53:35.943     201612   201710
 2   a    c   2 2016-12-05 07:53:35.943     201612   201710}

 # Extract a single dataframe
 df_2015 = dict_of_df['df_new_201511']
2 of 2
1

There is a more easy way to accomplish this using exec method. The following steps can be done to create a dataframe at runtime.

1.Create the source dataframe with some random values.

import numpy as np
import pandas as pd
    
df = pd.DataFrame({'A':['-a',1,'a'], 
                   'B':['a',np.nan,'c'],
                   'ID':[1,2,2]})

2.Assign a variable that holds the new dataframe name. You can even send this value as a parameter or loop it dynamically.

new_df_name = 'df_201612'

3.Create dataframe dynamically using exec method to copy data from source dataframe to the new dataframe dynamically and in the next line assign a value to new column.

exec(f'{new_df_name} = df.copy()')
exec(f'{new_df_name}["new_col"] = 123') 

4.Now the dataframe df_201612 will be available on the memory and you can execute print statement along with eval to verify this.

print(eval(new_df_name))
🌐
AskPython
askpython.com › home › python pandas dynamically create a dataframe
Python Pandas Dynamically Create a Dataframe - AskPython
July 20, 2023 - Dynamically creating a dataframe is an efficient way of creating a dataframe due to various reasons which are mentioned above in this article. So, let’s get started to make our process more dynamic. cols = ["Company Name", "Price"] data = [("Mahindra", 10000), ("TATA", 20000), ("Toyota",30000)]
🌐
Medium
vnimmana.medium.com › creating-dynamic-dataframes-using-dictionary-d2b0dfd3262c
Creating Dynamic Dataframes Using Dictionary | by Vijay Krishna Nimmana | Medium
December 27, 2020 - Creating Dynamic Dataframes Using Dictionary In this tutorial, we will discuss about reading multiple files in to dataframes and append all the files to form a single dataframe. Photo by Fré …
🌐
Reddit
reddit.com › r/learnpython › renaming a data frame based on dynamic global variable
r/learnpython on Reddit: Renaming a data frame based on dynamic global variable
March 15, 2023 -

I have a data frame patient_info in a function . My global variables are year =20 and pat_type = ‘DD’ . I want to rename the data frame as DD_patient_info_20.

I have been using f strings and + but it does not let me assign as follows

name =pat_type+’patient_info_’+str(year)= patient_info

How can I rename the data frame based on the dynamic variables

Edit :

Took your suggestion of not using type so renamed that variable to pat_type

I ended up using : Global()[name]=patient_info and that worked for me . Is there anything wrong in this method ?

🌐
Python Forum
python-forum.io › thread-21151.html
dynamically create variables' names in python
May 14, 2021 - Hi guys, i want to create variables in the following way: assign a name (e.g. var1), then add the name to the prefix of the variable: name = 'var_1' this_is_+name = pd.DataFrame()the outcome i would l
🌐
YouTube
youtube.com › watch
How To Create a DataFrame Dynamically in Python #coding #python #dataframe #datascience #tutorial - YouTube
This video shows how to create a Data Frame in Python dynamically.Find the code in my Github:https://github.com/Gravimotion/Youtube/blob/main/CreateDFDynmica...
Published   July 23, 2022
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › dynamically assigning name of dataframe in a loop. stuck!
r/learnpython on Reddit: Dynamically assigning name of dataframe in a loop. Stuck!
February 2, 2018 -

Going pseudo-code this out, perhaps somebody has encountered this sort of issue before. Have not had luck reading through stackoverflow posts.

I have a list of months and a df for each month with data that includes delivery volume and a time. These named like 'df_1701_unfiltered'.

I previously hardcoded my query logic, but on mobile now. That's not what I'm worried about so please disregard the pseudo aspect (I'm on mobile atm).

I want to create a new, separate dataframe for each month that is a filtered version of the original. Here is my thought process.

months = ['1701', '1702', '1703']

For month in month: "df_"+month+"filtered" = "df"+month+"_unfiltered".query("time > start and time < end")

I'm able to do something similar within a single dataframe using .apply to create dynamic columns. It throws an "cannot assign to operator" error each time.

Any idea how I can do this for entire dataframes?

🌐
Stack Overflow
stackoverflow.com › questions › 46311133 › creating-dynamic-data-frames-in-python
pandas - Creating Dynamic Data Frames in Python - Stack Overflow
September 20, 2017 - I was able to solve the problem by adding a line DF["Name"] = pd.DataFrame([i] *len(DF1),columns="Name")) – JRK Commented Sep 20, 2017 at 21:30 · Add a comment | The Overflow Blog · The ghost jobs haunting your career search · Breaking up is hard to do: Chunking in RAG applications · Featured on Meta · The December 2024 Community Asks Sprint has been moved to March 2025 (and... Stack Overflow Jobs is expanding to more countries · 1 Create dynamic columns in dataframe using pandas · 6 Python Pandas Dynamically Create a Dataframe ·
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.24.2 › user_guide › cookbook.html
Cookbook — pandas 0.24.2 documentation
the following Python code will read the binary file 'binary.dat' into a pandas DataFrame, where each element of the struct corresponds to a column in the frame: names = 'count', 'avg', 'scale' # note that the offsets are larger than the size of the type because of # struct padding offsets = 0, 8, 16 formats = 'i4', 'f8', 'f4' dt = np.dtype({'names': names, 'offsets': offsets, 'formats': formats}, align=True) df = pd.DataFrame(np.fromfile('binary.dat', dt))
🌐
Saturn Cloud
saturncloud.io › blog › python-pandas-dynamically-create-a-dataframe-a-guide
Python Pandas Dynamically Create a Dataframe A Guide | Saturn Cloud Blog
October 4, 2023 - One of the easiest ways to create a dataframe dynamically is by using a Python dictionary. We can create a dictionary with keys representing the column names and values representing the data for each column.
🌐
Stack Overflow
stackoverflow.com › questions › 54990451 › dynamic-dataframe-names-creation
python - Dynamic dataframe names creation - Stack Overflow
whole_dataframes = {} #k = int(np.floor(float(X.shape[0]) / number_folds)) weights = np.zeros((3,num_portfolios)) for lambda_ in range(0,len(tuned_parameter)-1): print ('....................................',lambda_) i=0 appended_data = [] for train_index, test_index in kf.split(X): print("Train:", train_index, "Validation:",test_index) X_train, X_test = X.iloc[train_index], X.iloc[test_index] print ('X train ............',X_train.shape) print ('X_test...............',X_test.shape) mean_returns_Train = X_train.mean() cov_matrix_Train=X_train.cov() mean_returns_Test = X_test.mean() cov_matrix_T
🌐
Saturn Cloud
saturncloud.io › blog › how-to-create-a-new-dataframe-in-pandas-with-dynamic-names-and-add-a-new-column
How to Create a New DataFrame in Pandas with Dynamic Names and Add a New Column | Saturn Cloud Blog
September 8, 2023 - Sometimes, you may want to create a new DataFrame with a dynamic name, such as when you are creating multiple DataFrames in a loop. To do this, you can use Python’s string formatting to generate a new name for each DataFrame.
🌐
Homedutech
homedutech.com › program-example › how-to-name-dataframes-dynamically-in-python.html
How to name dataframes dynamically in Python?
Description: Dynamically names multiple dataframes in a loop using the globals() function. ... Description: Creates a DataFrame with a dynamic column name.
🌐
Towards Data Science
towardsdatascience.com › home › latest › data wrangling solutions – dynamically creating variables when slicing dataframes
Data Wrangling Solutions - Dynamically Creating Variables When Slicing Dataframes | Towards Data Science
January 29, 2025 - The first value, 70, is the year of manufacturing, and the second value is the sliced dataframe itself. Finally, we will convert the tuple object into a dictionary using the python function dict. #### Converting the tuple object to a dictionary dictionary_tuple_groupby_df = dict(tuple_groupby_df) The dictionary created in the last step is the workaround solution we were referring to in the tutorial. The only difference between this solution and the manual creation of actual variables is the variable names.