【问题标题】:fill in missing DataFrame indices填写缺失的 DataFrame 索引
【发布时间】:2017-07-03 16:13:39
【问题描述】:

给定两个 pandas 数据框 dfadfb,如何确保每个 DataFrame 的 MultiIndex 包含另一个数据框的所有行?

In [147]: dfa
Out[147]: 
        c
a b      
0 5  10.0
1 6  11.0
2 7  12.0
3 8  13.5
4 9  14.0

In [148]: dfb
Out[148]: 
      c
a b    
0 5  10
2 7  12
3 8  13
4 9  14

这里,dfb 缺少索引 (1, 6):

In [149]: dfa - dfb
Out[149]: 
       c
a b     
0 5  0.0
1 6  NaN
2 7  0.0
3 8  0.5
4 9  0.0

...但dfa 也可能缺少来自dfb 的索引。该值应该是0,我们在每个数据帧中插入一个缺失的索引。

换句话说,每个 DataFrame 的索引应该是两个 MultiIndex 的并集,其中添加的行的值是 0。

【问题讨论】:

    标签: pandas dataframe union nan multi-index


    【解决方案1】:

    对于所有出现的 MultiIndex 值完整笛卡尔积的扩展,这很好用:

    from itertools import product
    
    df = dfa.loc[0:2]
    print(df)
    
            c
    a b      
    0 5  10.0
    1 6  11.0
    2 7  12.0
    
    # build full cartesian product index
    cpr_index = product(*(df.index.get_level_values(icol) for icol in df.index.names))
    # and generate the missing elements, filling with -1
    print(df.reindex(cpr_index, fill_value=-1))
    
            c
    a b      
    0 5  10.0
      6  -1.0
      7  -1.0
    1 5  -1.0
      6  11.0
      7  -1.0
    2 5  -1.0
      6  -1.0
      7  12.0
    

    基本上这会创建一个填充默认值的完全填充的张量或矩阵。 对于部分完整人口(例如:对于所有 a >= 1),必须相应地制作产品。

    【讨论】:

      【解决方案2】:

      如果需要将NaN 替换为某个值,我认为您需要带有参数fill_valueDataFrame.sub

      df = dfa.sub(dfb, fill_value=0)
      print (df)
              c
      a b      
      0 5   0.0
      1 6  11.0
      2 7   0.0
      3 8   0.5
      4 9   0.0
      
      df = dfb.sub(dfa, fill_value=0)
      print (df)
            c
      a b    
      0 5  10
      1 6   0
      2 7  12
      3 8  13
      4 9  14
      

      或者如果需要union的索引添加reindex:

      mux = dfa.index.union(dfb.index)
      print (mux)
      MultiIndex(levels=[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]],
                 labels=[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]],
                 names=['a', 'b'],
                 sortorder=0)
      
      print (dfa.reindex(mux, fill_value=0))
              c
      a b      
      0 5  10.0
      1 6  11.0
      2 7  12.0
      3 8  13.5
      4 9  14.0
      
      print (dfb.reindex(mux, fill_value=0))
            c
      a b    
      0 5  10
      1 6   0
      2 7  12
      3 8  13
      4 9  14
      

      【讨论】:

        猜你喜欢
        • 2017-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-19
        • 2018-06-24
        相关资源
        最近更新 更多