0

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @enke. However, here I only provide a very simple example. I have to use the loop. I want to build a df which the x_0, x_1 and its columns should be filled with RMSE and MAPE metrics which calculated in a loop. And in the loop, when I use df[f'RMSE_{kk+1}' ] = RMSE in for that row, the final df has only one id.
@Sadcow Edited the code. See if it's something you have in mind.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.