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

给定索引位置的pandas concat数据帧

  •  0
  • rxmnnxfpvg  · 技术社区  · 7 年前

    我有一个带有multindex的dataframe,还有一个行向量,我想将其值连接到dataframe。列预先不存在于第一个数据帧上。例如:

    # First dataframe, lots of rows, index on (city, animal, zoo)
    city       animal   zoo
    boston     pig      bns
    new york   tiger    nycz
    [...]
    
    # Second dataframe, one row, non-label index 
        apple  banana   ...  grape
    0   5      10       ...  37
    

    I 知道 要将第二个数据帧添加到的索引(但不是行号): index = (boston, big, bns) .所以我试着做:

    first_dataframe[index, second_dataframe.columns] = second_dataframe
    

    但我得到了 KeyError 因为 second_dataframe 第一个还不存在。我想 merge join 可能是正确的,但它们需要共享索引。 concat 看起来很正确,但我不知道该怎么说 which 第一个数据框中的行应该得到第二个数据框。

    我想要的输出是:

    city       animal   zoo   apple  banana   ...  grape
    boston     pig      bns   0   5      10   ...  37
    new york   tiger    nycz  NaN NaN    NaN  ...  NaN
    [...]     
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   BENY    7 年前

    首先在df1中创建列,然后通过 .values loc

    index = ('boston', 'pig', 'bns')
    df1=df1.assign(**dict(zip(df2.columns,[np.nan]*df2.shape[1])))
    df1.loc[index,df2.columns]=df2.values
    df1
                         apple  banana  grape
    city    animal zoo                       
    boston  pig    bns     5.0    10.0   37.0
    newyork tiger  nycz    NaN     NaN    NaN
    LOL     L      L       NaN     NaN    NaN
    LOL1    L1     L1      NaN     NaN    NaN