Home > Blockchain >  Appending row to dataframe with concat()
Appending row to dataframe with concat()

Time:02-16

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?

CodePudding user response:

You can transform you dic 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)

CodePudding user response:

Concat needs a list of series or df objects as first argument.

import pandas as pd

my_dict = {'the_key': 'the_value'}

for key in my_dict:
   row = {'Name': 'name_test', 'Weight':'weight_test', 'Sample':'sample_test'}
   df = pd.concat([pd.DataFrame(row, index=[key])], axis=1, ignore_index=True) 

print(df)
         0          1           2
the_key name_test   weight_test sample_test

CodePudding user response:

Aren't you looking for this? Pandas concat dictionary to dataframe

  • Related