Mukul Mukul - 4 months ago 6
Python Question

how to create and append multiple rows using two loops in python

i need to create a dataframe such that i have the output as follows

day hour cal_hr
1 6 106
1 7 107
1 8 108
..
..
1 24 124
..
7 1 701
7 2 702
..
..
7 24 724


i want to loop through day and then hour and then do a concat of day and hour. With preceding 0 for 106(say)

something like

for i in range(1,8):
for j in range(6,25):
df.append(i,j)
df=pd.dataFrame(df)


can df.append create two variables simaltaneously

Answer

Append to a list then convert to a dataframe. It would be much more efficient.

df = pd.DataFrame([(i, j, 100*i+j) 
                    for i in range(1, 8) 
                    for j in range(6, 25)], 
                    columns=['day', 'hour', 'cal_hr'])

df.head()
Out[143]: 
   day  hour  cal_hr
0    1     6     106
1    1     7     107
2    1     8     108
3    1     9     109
4    1    10     110

df.tail()
Out[144]: 
     day  hour  cal_hr
128    7    20     720
129    7    21     721
130    7    22     722
131    7    23     723
132    7    24     724
Comments