Home > Back-end >  Python nested for loops, ordering
Python nested for loops, ordering

Time:09-28

I want to make a dataframe containing 3 columns. I have three different lists containing the values that need to be in the dataframe in a certain order, so I want to loop over the lists to combine them and create the dataframe.

  • List F, contains 9 values
  • List P, contains 3 values
  • List A, contains 3 values

The final dataframe will be exported in Excel and should look like this: |F |P |A | |----|----|----| |F(0)|P(0)|A(0)| |F(1)|P(0)|A(1)| |F(2)|P(0)|A(2)| |F(3)|P(1)|A(0)| |F(4)|P(1)|A(1)| |F(5)|P(1)|A(2)| |F(6)|P(2)|A(0)| |F(7)|P(2)|A(1)| |F(8)|P(2)|A(2)|

To achieve this, I wanted to first create a list with these values and split that in a dataframe.

I tried this to obtain the list:

df_test3 = []

for f in F:
    df_test3.append(f)
    for p in P:
        for a in D:
            df_test3.append(p)
            df_test3.append(a)

List P and A are in the correct order, but I can't match it with the outer loop F. I know I have to do something with break to return to the outer loop, but I can't see how.

It returns this now:

list = [F0, P0, A0, P0, A1, P0, A2, P1, A0, etc.] 

and continues to the next value of F after the inner loops are completed. How can I get all the values in the right order in the list? Or am I handling this the wrong way and should I create the dataframe right away?

CodePudding user response:

You can use cycle from itertools.

For example:

from itertools import cycle
F =[ 0,1,2,3,4,5,6,7,8]
P = [0,1,2]
A = [0,1,2]

df_test3 = []

zip_list = zip(F, cycle(P),cycle(A))
print(list(zip_list))

the result is: [(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 0, 0), (4, 1, 1), (5, 2, 2), (6, 0, 0), (7, 1, 1), (8, 2, 2)]

You can go through it. Maybe it could help you to get a solution.

CodePudding user response:

Try this...

F = [1,2,3,4,5,6,7,8,9]
P = [11,22,33]
A = [111,222,333]

P1 = []
num1 = int(len(F)/len(P))
for p in P:
    P1 = P1   [p]*num1

num2 = int(len(F)/len(A))
A1 = A*num2

df_result = pd.DataFrame({"F":F,"P":P1,"A":A1})

# Output of df_result...
   F   P    A
0  1  11  111
1  2  11  222
2  3  11  333
3  4  22  111
4  5  22  222
5  6  22  333
6  7  33  111
7  8  33  222
8  9  33  333

Hope this Helps...

  • Related