在数据帧上附加字典

我有一个函数,它返回这样的字典:

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

我试图把这本词典附加到一个数据框架中,如下所示:

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

不幸的是,打印数据框会导致一个空的数据框。有什么办法吗?

210437 次浏览

You don't assign the value to the result.

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

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())

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.