python - 将嵌套字典替换为空数据框
问题描述
我有以下内容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
用零填充的值,而不是替换值。
解决方案
如果可能的话,使用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
推荐阅读
- powershell - 使用 Where-Object 打开文件
- firebase - 在特定时间对谷歌通知的操作
- ios - 旧项目停止使用最新的模拟器更新进行构建
- python - Pandas:用于条目的优先级消除重复值
- jquery - 如何使用 jQuery 定位嵌套在另一个元素的兄弟标签中的元素
- tensorflow - tensorflow中处理多类多标签分类时如何计算准确率?
- php - 通过 API 自定义身份验证
- google-calendar-api - 为 FreeBusyReader 添加 ACL 记录
- active-directory - 如何在 Active Directory Explorer 中找到 CN/组所在的域
- c++ - 错误的自动演绎c++14