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

Time:05-10

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  

CodePudding user response:

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")

CodePudding user response:

You can initialize u outside of your loop increment u and use as index to the second dataframe.

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:
            for i in range(0,20):
                try:
                        f.write(" & ".join([str(x) for x in results_table2.iloc[u]])   " \\\\\n")
                        u  = 1
                except:
                        pass
f.close()
  • Related