简体   繁体   中英

Assigning variables over multiple DataFrames

I have 5 separate DataFrames, person1 - person5 where id is the column name. I want to assign the id column of each DataFrame to a variable. I have to copy and paste text often because I don't know how to loop over the DataFrames. I tried using eval and exec along with other methods but with no success.

id1 = person1.id
id2 = person2.id
id3 = person3.id
id4 = person4.id
id5 = person5.id

You may be able to do it like this:

for x in range(1,6): 
  exec(f'id{x} = person{x}.id') 

you can put your dataframes into a list and then loop through the list:

ldf = [person1,person2,person3,person4,person5]
lid = {}
for i in range(1, len(ldf)+1):
    lid[f'id{i}'] = ldf[i].id

Now you have all your id in a lid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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