How do you give a dataframe name dynamically in python?

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a string input, our task is to write a Python program to create a variable from that input (as a variable name) and assign it to some value. Below are the methods to create dynamically named variables from user input.

    Using globals() method to create dynamically named variables

    Here we are using the globals() method for creating a dynamically named variable and later assigning it some value, then finally printing its value.

    Python3

    Dynamic_Variable_Name = "geek"

    globals()[Dynamic_Variable_Name] = 2020

    print(geek)

    Output:

    2020

    Using locals() method to create dynamically named variables

    Here we are using the locals() method for creating dynamically named variable and later assigning it some value, then finally printing its value.

    Python3

    Dynamic_Variable_Name = "geek"

    locals()[Dynamic_Variable_Name] = 2020

    print(geek)

    Output:

    2020

    Using exec()method to create dynamically named variables

    Here we are using the exec() method for creating dynamically named variable and later assigning it some value, then finally printing its value.

    Python3

    Dynamic_Variable_Name = "geek"

    exec("%s = %d" % (Dynamic_Variable_Name, 2020))

    print(geek)

    Output:

    2020

    Using vars()method to create dynamically named variables

    Here we are using the vars() method for creating dynamically named variable and later assigning it some value, then finally printing its value.

    Python3

    Dynamic_Variable_Name = "geek"

    vars()[Dynamic_Variable_Name] = 2020

    print(geek)

    Output:

    2020

    How do you give a dataframe name dynamically in python?
    How do you give a dataframe name dynamically in python?

    Datasnips was built out of frustration in wasting time searching for Data Science & AI code snippets through old projects, documentation and internet sources.

    We wanted a platform to easily find & organise our snippets, to share them with the community and discover those shared by other users.

    At Datasnips you can quickly search, discover and bookmark snippets from the community, curate your own snippet library for easy reference and share your own snippets for others to use.

    Our aim is for Datasnips to be the place where everyone can find the code snippet they need. Sign up to be part of the community.

    How do you give a dataframe name dynamically in python?

    • Code Snippets
    • Blog
    • Login

    Python

    Data Preprocessing

    In this example both the values in the columns and the column names are created dynamically.

    Here we dynamically create three columns that multiply the column A in our dataframe by each of the numbers in the list "multipliers".

    multipliers = [2,3,4]
    for i in multipliers:
        df[f'times_{i}'] = df['A'] * i
    
    df.columns
    
    >> Index(['A', 'B', 'times_2', 'times_3', 'times_4'], dtype='object')

    By detro - Last Updated March 29, 2022, 7:34 p.m.

    How do you give a dataframe name dynamically in python?

    Did you find this snippet useful?

    Sign up to bookmark this in your snippet library

    COMMENTS

    RELATED SNIPPETS

    Find Snippets by Language

    Find Snippets by Use

    Question :

    Create new dataframe in pandas with dynamic names also add new column

    I have a dataframe df

     df = pd.DataFrame({'A':['-a',1,'a'], 
                   'B':['a',np.nan,'c'],
                   'ID':[1,2,2],
                    't':[pd.tslib.Timestamp.now(),pd.tslib.Timestamp.now(),
                        np.nan]})
    

    Added a new column

    df['YearMonth'] = df['t'].map(lambda x: 100*x.year + x.month)
    

    Now I want to write a function or macro which will do date comparasion, create a new dataframe also add a new column to dataframe.

    I tried like this but seems I am going wrong:

    def test(df,ym):
        df_new=df
        if(ym <= df['YearMonth']):
            df_new+"_"+ym=df_new
            return df_new+"_"+ym
        df_new+"_"+ym['new_col']=ym
    

    Now when I call test function I want a new dataframe should get created named as df_new_201612 and this new dataframe should have one more column, named as new_col that has value of ym for all the rows.

    test(df,201612)
    

    The output of new dataframe is:

    df_new_201612

    A   B   ID  t                           YearMonth   new_col
    -a  a   1   2016-12-05 12:37:56.374620  201612      201612 
    1   NaN 2   2016-12-05 12:37:56.374644  201208      201612 
    a   c   2   nat                         nan         201612 
    

    Answer #1:

    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']
    

    How do you name a DataFrame dynamically?

    Here is how we can do that:.
    Create an empty Dictionary. This will hold our key-value pairs from the For Loop..
    Start a For Loop using files as our iterator..
    Assign a name to the key. In my case, I am using the name of the file..
    Read the DataFrame using pd. read_csv..
    Add the key-value pair to the dictionary..

    How do you assign a name to a DataFrame in Python?

    To rename the columns of this DataFrame , we can use the rename() method which takes:.
    A dictionary as the columns argument containing the mapping of original column names to the new column names as a key-value pairs..
    A boolean value as the inplace argument, which if set to True will make changes on the original Dataframe..

    How do you get a DataFrame feature name?

    You can get the Pandas DataFrame Column Names by using DataFrame. columns. values method and to get it as a list use tolist(). Each column in a Pandas DataFrame has a label/name that specifies what type of value it holds/represents.

    How do I rename an entire data frame?

    It's quite simple to rename a DataFrame column name in Pandas. All that you need to do is to use the rename() method and pass the column name that you want to change and the new column name.