首页 > 解决方案 > 将嵌套字典替换为空数据框

问题描述

我有以下内容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. 并在列中key找到每个 的值nested_dict

            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       

我想将values.values()ofnested_dict放在 中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用零填充的值,而不是替换值。

标签: pythonpandasdictionarydataframe

解决方案


如果可能的话,使用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

推荐阅读