In python pandas, How to apply loop to create rows for multiple columns?

import pandas as pd
import numpy as np


column_names = [str(x) for x in range(1,4)]

df= pd.DataFrame ( columns = column_names )

new_row = []

for i in range(3):
    new_row.append(i)


df = df.append(new_row , ignore_index = True) 


print(df)

output:

     1    2    3    0
0  NaN  NaN  NaN  0.0
1  NaN  NaN  NaN  1.0
2  NaN  NaN  NaN  2.0

Is there a way to apply the loop to column 1, column 2, and column 3?

I think it’s possible with a simple code, isn’t it?

I’ve been thinking a lot, but I don’t know how.

I also tried the .loc() method, but I couldn’t apply the loop to the row of columns.


This is a supplementary explanation.

‘column_names = [str(x) for x in range(1,4)]’ creates columns 0 to 3.

A loop is applied to each column.

The “for” loop inserts 0 through 2 into column 1.

Therefore, 0, 1, 2 are input to the row of column 1.

The result I want is below.


Answer

You can add the following code after all your codes above:

for col in df:
    df[col] = new_row

Result:

If you run after all your codes:

column_names = [str(x) for x in range(1,4)]

df= pd.DataFrame ( columns = column_names )

new_row = []

for i in range(3):
    new_row.append(i)

df = df.append(new_row , ignore_index = True) 

Then run the code here:

for col in df:
    df[col] = new_row

You should get:

print(df)

   1  2  3  0
0  0  0  0  0
1  1  1  1  1
2  2  2  2  2