简体   繁体   English

重命名数据框名称python

[英]Rename Dataframe name python

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.目标是每个变量都获得数据框名称。

For dynamic variable names in python, see How can you dynamically create variables?有关 python 中的动态变量名称,请参阅如何动态创建变量?

The way to do it is to make a dictionary where the key is the name and the value is the dataframe db .这样做的方法是制作一个dictionary ,其中key是名称, value是数据框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

I start by saying that what you are doing is probably not good practice.我首先说你正在做的可能不是好的做法。 This can probably be solved with dict .这可能可以用dict解决。

Anyway I think locals() can come in handy.无论如何,我认为locals()可以派上用场。

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.如您所见,循环之前不存在 var0、var1 和 var2。 You can find more Here !你可以在这里找到更多!

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,最好的,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM