我有以下内容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_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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句