Skip to content
Advertisement

why does nested loop start from 0 and how to change it to start from where it had left?

I want to generate a code that will write 20 rows from each of two different dataframes. Therefore, I created something like below. Everything works fine except nested loop (u) starts from 0 each time. Can you help me how to fix it to start from where it left, please?

 for t, row in results_table1.iterrows():
    f.write(" & ".join([str(x) for x in row.values]) + " \\n")
    if t > 0 and t % 20 == 0:
        for u, row in results_table2.iterrows():
            f.write(" & ".join([str(x) for x in row.values]) + " \\n")
            if u > 0 and u % 20 == 0:
                break  

Advertisement

Answer

Do you want to alternate between the two tables? Then I would just access the content by index:

for t in range(20):
    f.write(" & ".join([str(x) for x in results_table1.iloc[t].values]) + " \\n")
    f.write(" & ".join([str(x) for x in results_table2.iloc[t].values]) + " \\n")

Edit: to get line 0-19 from table 1, then 0-19 from table 2, then 20-39 from table one etc:

(based on the answer of im_vutu but making sure all lines are copied, even if the total is not divisible by 20)

u = 0
for t, row in results_table1.iterrows():
    f.write(" & ".join([str(x) for x in row.values]) + " \\n")
    if t > 0 and t % 20 == 0 or t == len(results_table1.index)-1:
        for i in range(0,20):
            try:
                f.write(" & ".join([str(x) for x in results_table2.iloc[u]]) + " \\n")
                u += 1
            except KeyError:
                break
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement