将单索引数据框添加到多索引数据框,Pandas,Python [英] Add single index data frame to multi index data frame, Pandas, Python

查看:114
本文介绍了将单索引数据框添加到多索引数据框,Pandas,Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将单个数据帧添加到多索引数据帧? 例如

how to add single data frame to multi index data frame? for example

我的多索引数据是

                Name  Code  Buying_Date  Buying_Price  Buying_Qty  

Date     Code                                                      
20140117 none   a   1234          20170101           5         7   
20170120 none   b   5678          20180101           6         8   

我希望将以下数据添加到'Date'='20170120'

and i desire to add following data to 'Date' = '20170120'

                Name  Code  Buying_Date  Buying_Price  Buying_Qty  

  Code                                                      
  abcd           af   abcd   20170101           5         7   
  efgh           bf   efgh   20180101           6         8   

期望结果是

               Name  Code  Buying_Date  Buying_Price  Buying_Qty  

Date     Code                                                      
20140117 none   a   1234          20170101           5         7   
20170120 none   b   5678          20180101           6         8  
         abcd   af  abcd          20170101           5         7   
         efgh   bf  efgh          20180101           6         8   

提前感谢您的建议.

推荐答案

您可以使用:

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                                                          
20140117 none     20170101             5           7   NaN  1234.0    a
20170120 none     20180101             6           8   NaN  5678.0    b
         abcd     20170101             5           7  abcd     NaN   af
         efgh     20180101             6           8  efgh     NaN   bf

详细信息:

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     20170101             5           7
         efgh   bf  efgh     20180101             6           8

说明:

  1. 第一个 assign 新列,然后通过 set_index
  2. MultiIndex
  3. swaplevel的水平
  4. 最后一个 append 第一个DataFrame
  1. First assign new column and add to index by set_index
  2. swaplevel of levels in MultiIndex
  3. Last append to first DataFrame

这篇关于将单索引数据框添加到多索引数据框,Pandas,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆