Home > Blockchain >  Fill a dataframe with the output of a loop
Fill a dataframe with the output of a loop

Time:07-06

I'm trying to concatenate the output of a loop into dataframe. This example is totally unrealistic, but just to try to demonstrate my problem, my error and the result I need.

for a in range(1,4):

    list1 = ["22", "23", "24", "25"]
    list2 = ["a", "b", "c", "d"]
    
    df = pd.DataFrame({'Num': list1,'Alpha': list2})

    print(df)

My output:

enter image description here

Good output

   Num Alpha
0  22     a
1  23     b
2  24     c
3  25     d
4  22     a
5  23     b
6  24     c
7  25     d
8  22     a
9  23     b
10 24     c
11 25     d

CodePudding user response:

This is one way to do it using your code above. Create an empty list before your for loop and append the df to it. Then concat the final list.

l = []   

for a in range(1,4):
    list1 = ["22", "23", "24", "25"]
    list2 = ["a", "b", "c", "d"]
    
    df = pd.DataFrame({'Num': list1,'Alpha': list2})

    l.append(df)

df = pd.concat(l)

CodePudding user response:

Use pd.concat with *3 instead of looping through a range of 3:

import pandas as pd
list1 = ["22", "23", "24", "25"]
list2 = ["a", "b", "c", "d"]
df = pd.concat([pd.DataFrame({'Num': list1,'Alpha': list2})] * 3).reset_index(drop=True)
df
Out[1]: 
   Num Alpha
0   22     a
1   23     b
2   24     c
3   25     d
4   22     a
5   23     b
6   24     c
7   25     d
8   22     a
9   23     b
10  24     c
11  25     d

CodePudding user response:

You can do

l = []
for a in range(1, 4):
    
    list1 = ["22", "23", "24", "25"]
    list2 = ["a", "b", "c", "d"]
    l.append(pd.DataFrame({'Num': list1, 'Alpha': list2}))
out = pd.concat(l,ignore_index = True)
  • Related