Home > Mobile >  Pandas : Append a dataframe to particular index in a multi-index dataframe
Pandas : Append a dataframe to particular index in a multi-index dataframe

Time:08-18

Say I have a dataframe :

index = pd.MultiIndex.from_product([["A", "B"], ["AA", "BB"]])
columns = ["X", "Y"]
df = pd.DataFrame([[1,2],[5,8],[1,2],[5,8]], index = index, columns = columns)

      X  Y
A AA  1  2
  BB  5  8
B AA  1  2
  BB  5  8

I want to append insert a dataframe with index value C to the same dataframe

df2 = pd.DataFrame([[1,4], [5,6]], index =  ["AAA", "BBB"], columns = columns)

     X  Y
AAA  1  4
BBB  5  6

So that my dataframe looks like

Expected Output :

        X    Y
A   AA  1    2
    BB  5    8
B   AA  1    2
    BB  5    8
C  AAA  1    4
   BBB  5    6

What I tried :

df.loc['C',:] = df2

which does NOT give me expected output

        X    Y
A AA  1.0  2.0
  BB  5.0  8.0
B AA  1.0  2.0
  BB  5.0  8.0
C     NaN  NaN

CodePudding user response:

Try to add a new index level to df2 first:

df.append(pd.concat({'C': df2}))

As @ouroboros mentioned df.append is being deprecated, the suggested syntax is now pd.concat([df, pd.concat({'C': df2})])

  • Related