将嵌套字典替换为空datafram

2024-05-20 02:32:16 发布

您现在位置: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的键上。在列中,在每个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       

我想将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,而不是替换值。你知道吗


Tags: keyviewdfdictemptynestedvaluesuk
2条回答

从字典构造数据帧并使用^{}

df_data = pd.DataFrame.from_dict(d, orient='index')

df.update(df_data)

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

如果可能,使用^{}并用^{}替换空值:

df = pd.DataFrame.from_dict(d, orient='index').fillna(0)

也可以为相同的列和索引名添加^{},顺序相同,如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

相关问题 更多 >