代码之家  ›  专栏  ›  技术社区  ›  user31415629

为什么我的数据总和在合并中会发生变化?

  •  0
  • user31415629  · 技术社区  · 6 年前

    我有两个数据帧, sales plan 如下:

                                      units
      retailer  product  date 
    
      1         1        2018-12-30   355
      1         1        2017-12-31   312
      1         1        2018-01-01   370
      ...
    
    
                                      plan_units
      retailer  product  date
      1         1        2018-01-01   360
      1         1        2018-01-02   380
      1         1        2018-01-03   330
      ...
    

    [retailer, product, date] 是索引。

    在合并之前, sales['units'].sum() 是123456。然而:

    pd.merge(sales, plan, left_index=True, right_index=True, how='outer')['units'].sum() 
    

    二十五万七千三百七十九 ,比以前多了。

    两个数据帧的索引不相同,因此 how='outer' . 然而,我怎么会在合并的结果中得到更多呢?

    1 回复  |  直到 6 年前
        1
  •  2
  •   BENY    6 年前

    例如,即使使用concat,也会遇到同样的问题,因为默认值是 outer .

    pd.concat([sales,plan],1)['units'].sum()
    

    例子:

    df1=pd.DataFrame({'key':[1,1,2],'val':[1,1,1]})
    df2=pd.DataFrame({'key':[1,1,2],'val':[1,1,1]})
    df1.merge(df2,on='key')
    Out[291]: 
       key  val_x  val_y
    0    1      1      1
    1    1      1      1
    2    1      1      1
    3    1      1      1
    4    2      1      1