0

I was iterating over a data frame as below:

for j in set(df.month):
    for i in set(df.place):
          print(j,i)

is there any way i can combine these for loop to a single one?

  • It is already answered here: https://stackoverflow.com/questions/9394803/python-combine-two-for-loops – Desert Eagle Aug 22 '22 at 17:19
  • if you have to iterate over both in an O(n^2) fashion, then I would recommend sticking with the two for loops. You could use @AKX 's way, but imho the double for loop is easier to comprehend what is occuring. Is there a reason you would want it in a single for loop? – Mitchnoff Aug 22 '22 at 17:19
  • which take less time complexity? using two for loop or a single loop? I think its single loop. Am i getting it right? – Mathew John Aug 22 '22 at 17:30
  • @MathewJohn in terms of time complexity they are the same -- just written differently. Regardless of which iterating structure you use, you will be iterating over the same number of elements. For example, if we were to increase the number of elements in the place column, both ways of doing this will increase the same amount. I see where you are coming from though with the idea of one for loop. – Mitchnoff Aug 22 '22 at 17:38
  • 1
    At the end of the day you need to think about what data you are iterating over -- the structures do not change what data you need to iterate over. I believe if you just iterated over months, for example, it would be O(n). Same goes for places. Since you are iterating over combinations of both (for every month, there is a pair with the place, and vice versa). Since the loops rely on the number of elements in months (n) and the number of elements in places (n), both ways of iterating will be O(n^2). There is no way to minimize this. Hope that helped clear things up! – Mitchnoff Aug 22 '22 at 17:41

1 Answers1

0

If you really need to, you can do that with itertools.product.

import itertools

for j, i in itertools.product(set(df.month), set(df.place)):
    print(j, i)
AKX
  • 152,115
  • 15
  • 115
  • 172