将嵌套字典替换为空数据框

詹姆斯·哈德森81

我有以下内容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()nested_dictempty_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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章