将字典追加到数据框



>我有一个函数,它返回一个字典,如下所示:

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

遗憾的是,数据帧的打印会导致数据帧为空。有什么想法吗?

启动 pandas==2.0.0 不起作用自 1.4 起已弃用

您不会将值分配给结果。

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

上一个答案(用户 alex,回答时间为 2018 年 8 月 9 日 20:09(现在触发一条警告,指出追加到数据帧将在将来的版本中被弃用。

一种方法是将字典转换为数据帧并连接数据帧:

output = pd.DataFrame()
df_dictionary = pd.DataFrame([dictionary])
output = pd.concat([output, df_dictionary], ignore_index=True)
print(output.head())

我总是这样做,因为这种语法对我来说不那么混乱。 我相信建议使用连接方法。

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

请注意,iloc 方法不会以这种方式工作。

最新更新