Home > Enterprise >  Fill pandas dataframe with dictionary elements
Fill pandas dataframe with dictionary elements

Time:11-16

I have a dataframe df structured as well:

Name    Surname     Nationality
Joe      Tippy        Italian
Adam     Wesker       American

I would like to create a new record based on a dictionary whose keys corresponds to the column names:

new_record = {'Name': 'Jimmy', 'Surname': 'Turner', 'Nationality': 'Australian'}

How can I do that? I tried with a simple:

df = df.append(new_record, ignore_index=True)

but if I have a missing value in my record the dataframe doesn't get filled with a space, instead it leaves me the last column empty.

CodePudding user response:

IIUC replace missing values in next step:

new_record = {'Surname': 'Turner', 'Nationality': 'Australian'}
df = pd.concat([df, pd.DataFrame([new_record])], ignore_index=True).fillna('')

print (df)
   Name Surname Nationality
0   Joe   Tippy     Italian
1  Adam  Wesker    American
2        Turner  Australian

Or use DataFrame.reindex:

df = pd.concat([df, pd.DataFrame([new_record])].reindex(df.columns, fill_value='',  axis=1), ignore_index=True)

CodePudding user response:

A simple way if you have a range index:

df.loc[len(df)] = new_record

Updated dataframe:

    Name Surname Nationality
0    Joe   Tippy     Italian
1   Adam  Wesker    American
2  Jimmy  Turner  Australian

If you have a missing key (for example 'Surname'):

    Name Surname Nationality
0    Joe   Tippy     Italian
1   Adam  Wesker    American
2  Jimmy     NaN  Australian

If you want empty strings:

df.loc[len(df)] = pd.Series(new_record).reindex(df.columns, fill_value='')

Output:

    Name Surname Nationality
0    Joe   Tippy     Italian
1   Adam  Wesker    American
2  Jimmy          Australian
  • Related