【问题标题】:Replacing a nested dictionary into empty dataframe将嵌套字典替换为空数据框
【发布时间】:2018-10-23 10:41:44
【问题描述】:

我有以下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,而不是替换值。

【问题讨论】:

    标签: python pandas dictionary dataframe


    【解决方案1】:

    如果可能,使用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
    

    【讨论】:

      【解决方案2】:

      从您的字典中构造一个数据框并使用pd.DataFrame.update

      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
      

      【讨论】:

        猜你喜欢
        • 2014-05-10
        • 1970-01-01
        • 2021-11-28
        • 2022-01-07
        • 1970-01-01
        • 2021-08-30
        • 2018-08-14
        • 2015-10-06
        相关资源
        最近更新 更多