2017-08-25 146 views
2
In [88]: c 
Out[88]: 
         Address Name 
CustomerID        
10   Address for Mike Mike 
11   Address for Marcia Marcia 

In [89]: c.index 
Out[89]: Int64Index([10, 11], dtype='int64', name='CustomerID') 

In [90]: orders 
Out[90]: 
    CustomerID OrderDate 
0   10 2014-12-01 
1   11 2014-12-01 
2   10 2014-12-01 

In [91]: orders.index 
Out[91]: RangeIndex(start=0, stop=3, step=1) 

In [92]: c.merge(orders) 
--------------------------- 
MergeError: No common columns to perform merge on 

所以熊貓不能合併,如果指數在一個數據幀列具有相同的名稱,在第二個數據幀的另一列?熊貓在索引列上合併?

回答

7

你需要明確指定如何連接表。默認情況下,merge將選擇公用列名稱作爲合併密鑰。爲你的情況,

c.merge(orders, left_index=True, right_on='CustomID') 

另外,請閱讀文檔pandas.DataFrame.merge請。 希望這會有所幫助。

+0

thx,我現在正在閱讀各種書籍,很多信息:)感謝Rojeer! – DmitrySemenov

1

嘗試重指數:

c.reset_index().merge(orders) 
2

join方法不左默認連接(how='left'),並加入對dataframes的指標。所以orders數據框的索引設置爲CustomerId,然後加入。

# Create sample data. 
orders = pd.DataFrame(
    {'CustomerID': [10, 11, 10], 
    'OrderDate': ['2014-12-01', '2014-12-01', '2014-12-01']})  
c = pd.DataFrame(
    {'Address': ['Address for Mike', 'Address for Marcia'], 
    'Name': ['Mike', 'Marcia']}, 
    index=pd.Index([10, 11], dtype='int64', name='CustomerID')) 

# Join. 
>>> c.join(orders.set_index('CustomerID')) 
         Address Name OrderDate 
CustomerID           
10   Address for Mike Mike 2014-12-01 
10   Address for Mike Mike 2014-12-01 
11   Address for Marcia Marcia 2014-12-01 

或者,這merge會在這裏,您將加入c(左側數據框)索引和右側數據框中CustomerID列上的索引。確保指定how='left'以僅將正確數據框中的項目連接到右側數據框中的所有記錄(留下與l相等數量的行編號c)。 merge的默認行爲是內部聯接,其結果僅包含c中的那些在orders(儘管這可能是您期望的結果)中找到匹配項的記錄。

c.merge(orders, left_index=True, right_on='CustomerID', how='left')