Home > Software design >  Build a dataframe in a nested for loop
Build a dataframe in a nested for loop

Time:05-08

I have a nested for loop, and I want to build a dataframe with it. Here is an example of my code:

for id in range( 3):

    for i in range(2):
    
        x = i   id
    
        y = id-i
    

My ids are three, I want to put the value of x and y for each id in one row. The output of the above code is as follow:

enter image description here

Could you please help me with that? Thanks

CodePudding user response:

Instead of a nested loop, you could use numpy broadcasting to build x columns and y columns separately:

import numpy as np
inner_loop_lim = 2
id_lim = 3
df = pd.DataFrame({'id':range(id_lim)})
df[[f'x_{i}' for i in range(inner_loop_lim)]] = df[['id']].to_numpy()   np.arange(inner_loop_lim)
df[[f'y_{i}' for i in range(inner_loop_lim)]] = df[['id']].to_numpy() - np.arange(inner_loop_lim)

Output:

   id  x_0  x_1  y_0  y_1
0   0    0    1    0   -1
1   1    1    2    1    0
2   2    2    3    2    1

If you absolutely need a loop, you can try the following that build x and y lists iteratively:

x_list = []
y_list = []
for id_ in range(3):
    inner_x = []
    inner_y = []
    for i in range(2):
        inner_x.append(i   id_)
        inner_y.append(id_ - i)
    x_list.append(inner_x)
    y_list.append(inner_y)
df = pd.DataFrame({'id':range(3)})
df[[f'x_{i}' for i in range(2)]] = x_list
df[[f'y_{i}' for i in range(2)]] = y_list
  • Related