Home > Software engineering >  Is it possible to concat a dictionary to an empty DataFrame?
Is it possible to concat a dictionary to an empty DataFrame?

Time:10-26

When I run the following code:

import pandas as pd
data = {'age':{'sam': 1,
                'rye': 3,
                'lori':8,
                'chris':11,
                'sara':3}}
df = pd.DataFrame()
df = pd.concat([df, data])

I get this error:

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

I'm wondering if this action is possible or if I'm doing something incorrectly.

CodePudding user response:

You just need to make data into a DataFrame first:

>>> df = pd.concat([df, pd.DataFrame(data)])
>>> df
       age
chris   11
lori     8
rye      3
sam      1
sara     3

You could then concat further dictionaries to df in a loop.

  • Related