3

I have a variable

var=[name1,name2]

I have a dataframe also in a list

df= [df1, df2]

How do i assign df1 to name1 and df2 to name2 and so on.

EdChum
  • 376,765
  • 198
  • 813
  • 562
user2819398
  • 75
  • 1
  • 8

2 Answers2

1

If I understand correctly, assuming the lengths of both lists are the same you just iterate over the indices of both lists and just assign them, example:

In [412]:
name1,name2 = None,None
var=[name1,name2]
df1, df2 = 1,2
df= [df1, df2]
​
for x in range(len(var)):
    var[x] = df[x]
var

Out[412]:
[1, 2]

If your variable list is storing strings then I would not make variables from those strings (see How do I create a variable number of variables?) and instead create a dict:

In [414]:
var=['name1','name2']
df1, df2 = 1,2
df= [df1, df2]
d = dict(zip(var,df))
d

Out[414]:
{'name1': 1, 'name2': 2}
Community
  • 1
  • 1
EdChum
  • 376,765
  • 198
  • 813
  • 562
  • The var=['name1','name2'] contains strings. do we still iterate over the lists. Apologies for not including the string earlier and also the df1= m *n matrix – user2819398 Jul 15 '15 at 13:51
  • Sorry you want to make variables from a string name? Also my code just demonstrates how to iterate over 2 lists and overwrite the contents of one list with another – EdChum Jul 15 '15 at 14:04
  • Also I suggest you use a dict to achieve what you want: http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python – EdChum Jul 15 '15 at 14:05
  • When you say `m*n matrix` what does this mean, is this an array? – EdChum Jul 15 '15 at 14:06
0

To answer your question, you can do this by:

for i in zip(var, df):
     globals()[i[0]] = i[1]

And then access your variables. But proceeding this way is bad. You're like launching a dog in your global environment. It's better to keep control about what you handle, keep your dataframe in a list or dictionary.

Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87