0

I want to create a dataframe which name contains a variable. For example:

class = 10
'number'+str(class) = pd.DataFrame([[1,2], [3,4]], columns = ['a','b'])

this code should create a df named "number10":

if I change the variable class to: class = 9, this should create a df named "number9"

The problem is that I cant associate a name to a variable. It is possible with some function? In R I could do it with "assign(paste(...))



Edit I solve the problem! the solution would be:

locals()['number'+str(class)] = pd.DataFrame([[1,2], [3,4]], columns = ['a','b'])

or

globals()['number'+str(class)] = pd.DataFrame([[1,2], [3,4]], columns = ['a','b'])
  • 1
    I don't think assigning variables like this is generally considered good practice. Could you store the different dataframes in a list? – FChm Feb 27 '19 at 20:10
  • Would be more useful to assign variables, because I could create loops which would create a lot of DFs, and create function that would associate an input to the name of a new DF – André Segadas Figueiredo Feb 27 '19 at 20:30
  • 1
    No this would absolutely not be more useful. You should use a *container*, not dynamically creating variables. So use a list or a dict – juanpa.arrivillaga Feb 27 '19 at 20:31
  • Ask yourself, how are you going to *access* these dynamically created variables? Inevitably, you will end up messing with some namespace, which in python will eventually reduce to manipulating a dict. So just use a container to begin with. – juanpa.arrivillaga Feb 27 '19 at 20:34
  • Ok, thank you for the answer – André Segadas Figueiredo Feb 27 '19 at 21:07
  • Note, `locals()['number'+str(class)] ` **will not work generally**. Modifications to dict returned by `locals` **will not affect the actual local namespace**. If you happen to be in the global scope, `locals()` returns `globals()`, and there you *will see the effect*. **But you shouldn't be doing this to begin with**. – juanpa.arrivillaga Feb 27 '19 at 21:12
  • I will analyze do this by dictionary instead of locals() or globals() – André Segadas Figueiredo Feb 28 '19 at 16:40

0 Answers0