1

I have a process which I am able to loop through for values held in a list but it overwrites the final dataframe with each loop and I would like to append or concat the result of the loops into one dataframe. For example given below I can see 'dataframe' will populate initially with result of 'blah1', then when process finishes it has the result of 'blah2'

listtoloop = ['blah1','blah2']

for name in listtoloop:


    some process happens here resulting in

        dataframe = result of above process
1

3 Answers 3

8

The typical pattern used for this is to create a list of DataFrames, and only at the end of the loop, concatenate them into a single DataFrame. This is usually much faster than appending new rows to the DataFrame after each step, as you are not constructing a new DataFrame on every iteration.

Something like this should work:

listtoloop = ['blah1','blah2']
dfs = []
for name in listtoloop:
    # some process happens here resulting in
    # dataframe = result of above process
    dfs.append(dataframe)
final = pd.concat(dfs, ignore_index=True)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I think I managed to find another way similar, have also posted.
@Evan that is what thesilkworm gave in their answer here.
Yeah, I mentioned I had found a similar way and posted the link to that way also. Thankyou both, I was continuing to research after I asked and our paths crossed.
0

Put your results in a list and then append the list to the df making sure the list is in the same order as the df

listtoloop = ['blah1','blah2']
df = pd.DataFrame(columns="A","B")
for name in listtoloop:
    ## processes here

    to_append = [5, 6]
    df_length = len(df)
    df.loc[df_length] = to_append

1 Comment

Thankyou, I think I managed to find another way also, posted in answer.
0
data_you_need=pd.DataFrame()  
listtoloop = ['blah1','blah2']  
for name in listtoloop:     
    ##some process happens here resulting in          
    ##dataframe = result of above process    
    data_you_need=data_you_need.append(dataframe,ignore_index=True)

1 Comment

The potential issue with this one is it results in a FutureWarning message. frame.append is deprecated and will be removed from pandas in a future version. However, you can append to a list no problem. Additionally, it's less performant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.