134

I have a function, which returns a dictionary like this:

{'truth': 185.179993, 'day1': 197.22307753038834, 'day2': 197.26118010160317, 'day3': 197.19846975345905, 'day4': 197.1490578795196, 'day5': 197.37179265011116}

I am trying to append this dictionary to a dataframe like so:

output = pd.DataFrame()
output.append(dictionary, ignore_index=True)
print(output.head())

Unfortunately, the printing of the dataframe results in an empty dataframe. Any ideas?

martineau
  • 119,623
  • 25
  • 170
  • 301
cs0815
  • 16,751
  • 45
  • 136
  • 299

3 Answers3

216

Doesn't work starting pandas==2.0.0, deprecated since 1.4

You don't assign the value to the result.

output = pd.DataFrame()
output = output.append(dictionary, ignore_index=True)
print(output.head())
Gulzar
  • 23,452
  • 27
  • 113
  • 201
alex
  • 2,177
  • 2
  • 8
  • 4
  • 8
    output = output.append(dictionary, ignore_index=True) makes all the difference ... – cs0815 Aug 09 '18 at 20:15
  • 40
    oh. I expected dictionary append to work in place like list append, but it doesn't. – Aaron Bramson Dec 03 '19 at 12:04
  • 14
    As of v 1.4, `append` is deprecated in favor of `concat`. See [here](https://pandas.pydata.org/pandas-docs/stable/whatsnew/v1.4.0.html#whatsnew-140-deprecations-frame-series-append). – user650654 May 03 '22 at 02:28
112

The previous answer (user alex, answered Aug 9 2018 at 20:09) now triggers a warning saying that appending to a dataframe will be deprecated in a future version.

A way to do it is to transform the dictionary to a dataframe and the concatenate the dataframes:

output = pd.DataFrame()
df_dictionary = pd.DataFrame([dictionary])
output = pd.concat([output, df_dictionary], ignore_index=True)
print(output.head())
ZF007
  • 3,708
  • 8
  • 29
  • 48
K. Do
  • 1,256
  • 1
  • 7
  • 7
  • 6
    this should be the accepted answer. Since the other one (https://stackoverflow.com/a/51775051/7924573) is deprecated. – tschomacker Apr 07 '22 at 13:39
  • 1
    It's a pity this is now the accepted way of doing things. Adding a dict to a DF is super common for me and I always have to look up the correct way of doing it now – beyarkay Dec 22 '22 at 14:02
5

I always do it this way because this syntax is less confusing for me. I believe concat method is recommended though.

df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
>>>df 
col1  col2
0     1     3
1     2     4

d={'col1': 5, 'col2': 6} 
df.loc[len(df)]=d

>>>df 
col1  col2
0     1     3
1     2     4
2     5     6

Note that iloc method won't work this way.

pawelek69420
  • 134
  • 1
  • 5