Home > database >  Rename Dataframe name python
Rename Dataframe name python

Time:07-02

I want to change the name of an dataframe using variables.


db = pd.Dataframe()

sopa = ['cebola','batata']


for sopa_id in sopa: 

    sopa_id = db

I want that the output to be:

 cebola = db

 batata = db

The goal is that each one of the variable get the dataframe name.

CodePudding user response:

I start by saying that what you are doing is probably not good practice. This can probably be solved with dict.

Anyway I think locals() can come in handy.

for i in range(3):
    locals()["var" str(i)] = i
    
print(var0)
print(var1)
print(var2)

As you can see var0, var1 and var2 don't exist before the loop. You can find more Here!

CodePudding user response:

For dynamic variable names in python, see How can you dynamically create variables?

The way to do it is to make a dictionary where the key is the name and the value is the dataframe db. I would discourage dynamic variable names as a general rule though.

db = pd.DataFrame()
# -- Do whatever here to populate --
sopa = ['cebola','batata']

dataframeDict = {}
for sopa_id in sopa:
    dataframeDict[sopa_id] = db

CodePudding user response:

Thank you all, problem solved.

db = pd.Dataframe()

sopa = ['cebola','batata']


for sopa_id in sopa: 
    locals()["new_name_is_" str(sopa_id)] = db

best,

  • Related