cs0*_*815 11 python dataframe python-3.x pandas
我有一个函数,它返回一个这样的字典:
{'truth': 185.179993, 'day1': 197.22307753038834, 'day2': 197.26118010160317, 'day3': 197.19846975345905, 'day4': 197.1490578795196, 'day5': 197.37179265011116}
Run Code Online (Sandbox Code Playgroud)
我试图将这个字典附加到数据帧,如下所示:
output = pd.DataFrame()
output.append(dictionary, ignore_index=True)
print(output.head())
Run Code Online (Sandbox Code Playgroud)
不幸的是,数据帧的打印导致空数据帧.有任何想法吗?
小智 126
之前的答案(用户 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())
Run Code Online (Sandbox Code Playgroud)
小智 20
您不会将值分配给结果.
output = pd.DataFrame()
output = output.append(dictionary, ignore_index=True)
print(output.head())
Run Code Online (Sandbox Code Playgroud)
我总是这样做,因为这种语法对我来说不那么混乱。我相信虽然建议使用 concat 方法。
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
Run Code Online (Sandbox Code Playgroud)
请注意,iloc 方法不会以这种方式工作。