簡體   English   中英

當僅將一級索引用作鍵時,pandas與MultiIndex合並

[英]pandas merge with MultiIndex, when only one level of index is to be used as key

我有一個名為df1的數據框,具有2級MultiIndex(級別:'_ Date'和_'ItemId')。 “ _ItemId”的每個值都有多個實例,如下所示:

                              _SomeOtherLabel
 _Date            _ItemId     
 2014-10-05       6588921     AA
                  6592520     AB 
                  6836143     BA
 2014-10-11       6588921     CA
                  6592520     CB
                  6836143     DA 

我有一個名為df2的第二個數據幀,其中'_ItemId'被用作鍵(而不是索引)。 在此df中,_ItemId的每個值僅出現一次:

                  _ItemId       _Cat
  0               6588921       6_1
  1               6592520       6_1
  2               6836143       7_1

我想從df2恢復“ _Cat”列中的值,並將它們合並到df1中以獲取“ _ItemId”的適當值。 這幾乎是(我認為?)標准的多對一合並,只是左df的適當鍵是MultiIndex級別之一。 我嘗試了這個:

df1['_cat']=pd.merge(df1,df2,left_index=True, right_on='ItemId')  

但我得到了錯誤

   "ValueError: len(right_on) must equal the number of levels in the index of "left"

我想這很有意義,因為我的(左)索引實際上是由兩個鍵組成的。 如何選擇所需的一個索引級別? 還是有一種更好的合並方法?

謝謝

我可以想到兩種方法。

使用set_index()join()

>>> df1.join(df2.set_index('_ItemId'))
                   _SomeOtherLabel _Cat
_Date      _ItemId                     
2014-10-05 6588921              AA  6_1
           6592520              AB  6_1
           6836143              BA  7_1
2014-10-11 6588921              CA  6_1
           6592520              CB  6_1
           6836143              DA  7_1

或使用reset_index()merge()然后設置新的multiindex

我認為第一種方法應該更快,但不確定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM