Skip to content
Advertisement

Appending row to dataframe with concat()

I have defined an empty data frame with

df = pd.DataFrame(columns=['Name', 'Weight', 'Sample'])

and want to append rows in a for loop like this:

for key in my_dict:
   ...
   row = {'Name':key, 'Weight':wg, 'Sample':sm}
   df = pd.concat(row, axis=1, ignore_index=True) 

But I get this error

cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

If I use df = df.append(row, ignore_index=True), it works but it seems that append is deprecated. So, I want to use concat(). How can I fix that?

Advertisement

Answer

You can transform your dict in pandas DataFrame

import pandas as pd
df = pd.DataFrame(columns=['Name', 'Weight', 'Sample'])
for key in my_dict:
  ...
  #transform your dic in DataFrame
  new_df = pd.DataFrame([row])
  df = pd.concat([df, new_df], axis=0, ignore_index=True)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement