Skip to content Skip to sidebar Skip to footer

Add Single Index Data Frame To Multi Index Data Frame, Pandas, Python

how to add single data frame to multi index data frame? for example my multi index data is Name Code Buying_Date Buying_Price Buying_Qty Date Code

Solution 1:

You can use:

df = df1.append(df2.assign(Date=20170120).set_index('Date', append=True).swaplevel(0,1))
print (df)
               Buying_Date  Buying_Price  Buying_Qty  Code  Code.1 Name
Date     Code                                                          
20140117none2017010157   NaN  1234.0    a
20170120none2018010168   NaN  5678.0    b
         abcd     2017010157  abcd     NaN   af
         efgh     2018010168  efgh     NaN   bf

Detail:

print (df2.assign(Date=20170120).set_index('Date', append=True).swaplevel(0,1))
              Name  Code  Buying_Date  Buying_Price  Buying_Qty
Date     Code                                                  
20170120 abcd   af  abcd     2017010157
         efgh   bf  efgh     2018010168

Explanation:

  1. First assign new column and add to index by set_index
  2. swaplevel of levels in MultiIndex
  3. Last append to first DataFrame

Post a Comment for "Add Single Index Data Frame To Multi Index Data Frame, Pandas, Python"