Iterating a dataframe and updating (adding on to the existing) instead of it being replaced

Viewed 26

I have an empty dataframe which when passed through the loop, returns result that matches the condition present from the last value in the list instead of considering all of it's values.

The dataframe gets replaced for each of the condition in list, instead of being added to it.

I have tried empty_df.append(...), it still wouldn't work.

njobs = ['doc', 'phy', 'sci', 'math', 'stat']
empty_df = pd.DataFrame() 

for i in njobs:
    df_new = df.loc[df['title'] == i]
    
    
    empty_df['skills'] = df_new[['(Level 6)','(Level 5)',
                                     '(Level 4)','(Level 3)', '(Level 2)',
                                     '(Level 1)',
                                     '(Level 0)']]
    
    empty_df['cat_id'] = df_new[['(L6)','(L5)','(L4)','(L3)',
                             '(L2)','(L1)', 'ID']]
    
    empty_df['wt'] = df_new[['Weight']]
    
    empty_df['job'] = i
1 Answers

You can craete each time a new dataframe in the lopp and lastly can concatenate them using pd.concat([df_doc, df_phy,.. df_stat])

Related