我有以下nested_dict
:
{'view_0': {'spain': -1}, 'view_1': {'portugal': 0}, 'view_2': {'morocco': 1.0, 'france': -1.0}, 'view_3': {'germany': 0.5, 'italy': 0.5, 'uk': -0.5, 'ireland': -0.5}}
另一方面,我有以下 empty_df
,其中索引显示 nested_dict
的键。并在列中找到每个 nested_dict
值中的 key
。
spain portugal morocco france germany italy uk ireland
view_0 0 0 0 0 0 0 0 0
view_1 0 0 0 0 0 0 0 0
view_2 0 0 0 0 0 0 0 0
view_3 0 0 0 0 0 0 0 0
我想将 nested_dict
的 values.values()
放入 empty_df
中以获得以下输出:
spain portugal morocco france germany italy uk ireland
view_0 -1 0 0 0 0 0 0 0
view_1 0 0 0 0 0 0 0 0
view_2 0 0 1 -1 0 0 0 0
view_3 0 0 0 0 0.5 0.5 -0.5 -0.5
为了做到这一点,我尝试了
empty_df.replace(nested_dict)
但是返回用零填充的 empty_dict
,而不是替换值。
最佳答案
如果可能的话使用 DataFrame.from_dict
并将空值替换为 fillna
:
df = pd.DataFrame.from_dict(d, orient='index').fillna(0)
也可以添加 reindex
对于具有相同顺序的相同列和索引名称,如 empty_df
:
df = (pd.DataFrame.from_dict(d, orient='index')
.reindex(columns=empty_df.columns, index=df_empty.index)
.fillna(0))
print (df)
spain portugal morocco france germany italy uk ireland
view_0 -1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
view_1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
view_2 0.0 0.0 1.0 -1.0 0.0 0.0 0.0 0.0
view_3 0.0 0.0 0.0 0.0 0.5 0.5 -0.5 -0.5
关于python - 将嵌套字典替换为空数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52947009/