0

I would like to rename the name of the DataFrame with a name containing a variable.

rename = 'test'

df = pd.DataFrame({'num': [2, 4, 8, 0]})

f'df_{rename}' = df

But I get the following error message: "SyntaxError: can't assign to literal"

What I exepct as an output : df_test instead of df

Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
Laurent
  • 43
  • 1
  • 6
  • 1
    Why do you want to do this? – alani Aug 24 '20 at 20:07
  • To be able to easily change the dataframe name in the global variables – Laurent Aug 24 '20 at 20:24
  • It is theoretically possible to do what you show by use of `globals()` but there is almost certainly a better way to do this. And if you show here how you intend to **use** that variable once you have renamed it, then hopefully somebody will be able to suggest to you how else you might access it (almost certainly as a dictionary lookup). – alani Aug 24 '20 at 20:38

1 Answers1

1

TL;DR : Use your own custom dictionary with the variable name as it's key - is the best practice.

What You Asked For

You can create a variable with a custom name by adding it to the globals dictionary.

import pandas as pd

rename = 'test'

df = pd.DataFrame({'num': [2, 4, 8, 0]})

# Creating a variable with a custom name by adding it to globals
globals()[f'df_{rename}'] = df

print(df_test)

How To Have a Variable With Custom Name - According to Best-Practices

Use your own dictionary to keep up with your custom variables.


import pandas as pd

rename = 'test'

df = pd.DataFrame({'num': [2, 4, 8, 0]})

# Creating a custom dictionary for the custom variables
my_dataframes                       = dict()
custom_variable_name                = 'df_{rename}'
my_dataframes[custom_variable_name] = df

print(my_dataframes[custom_variable_name])
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22