2

I have several pandas dataframes (A,B,C,D) and I want to merge each one of them individually with another dataframe (E).

I wanted to write a for loop that allows me to run the merge code for all of them and save each resulting dataframe with a different name, so for example something like:

tables = [A,B,C,D]

n=0
for df in tables:
    merged_n = df.merge(E, left_index = True, right_index = True)
    n=n+1

I can't find a way to get the different names for the new dataframes created in the loop. I have searched stackoverflow but people say this should never be done (but couldn't find an explanation why) or to use dictionaries, but having dataframes inside dictionaries is not as practical.

2
  • Why would putting dataframes in a dictionary not be practical? It is the straightforward way to do what you're suggesting. Commented Sep 20, 2017 at 15:18
  • It may be because I am not used to working with dictionaries really, and I don't really understand why creating the new variables in a loop is such a bad idea... Commented Sep 21, 2017 at 7:50

1 Answer 1

1

you want to clutter the namespace with automatically generated variable names? if so, don't do that. just use a dictionary.

if you really don't want to use a dictionary (really think about why you don't want to do this), you can just do it the slow-to-write, obvious way:

ea = E.merge(A)
eb = E.merge(B)
...

edit: if you really want to add vars to your namespace, which i don't recommend, you can do something like this:

l = locals()
for c in 'abcd':
    l[f'e{c}'] = E.merge(l[c.upper()])
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please explain why it is not a good idea to automatically add variable names to the namespace? I see a lot of people saying that but never saw an explanation why...
@user5576 sure. it's because it's not explicit and clear (python.org/dev/peps/pep-0020). and it's usually a code smell. if you're programmatically creating a bunch of objects, you should operate on them in a programmatic way. instead of binding names n0..n25 to values, just put those values in a list and operate on them there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.