python - 将嵌套字典替换为空数据帧

标签 python pandas dictionary dataframe

我有以下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_dictvalues.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/

相关文章:

python - PyDev Unresolved sklearn 导入问题

python - 如何检测关闭的套接字或实现 Apple 推送通知提供程序

python - 我是否需要仅在构建 ATLAS 时或始终关闭 CPU 限制?

python - Scipy 拟合向量中的参数

python - pandas 将 2 个具有不同日期索引的数据帧组合在一起

python - 比较 python 中 sql 的两个列表并使用 pandas.io 显示结果

python - 将一行中的所有列追加到另一行中

Python修改字典列表中的值

c# - 从 Dictionary<Key, Item> 中移除元素

dictionary - 用new()初始化map,然后给panic异常赋值,为什么?