代码:
import pandas as pd
import numpy as np
right = pd.DataFrame(data=np.arange(12).reshape((6,2)),index=[['Nevada', 'Nevada', 'Ohio', 'Ohio', 'Ohio', 'Ohio'],[2001, 2000, 2000, 2000, 2001, 2002]],columns=['event1','event2'])
left = pd.DataFrame(data={'key1':['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],'key2':[2000, 2001, 2002, 2001, 2002],'data':np.arange(5.)})
pd.merge(left,right,right_index=True,left_index=True,right_on='event1')#it works and returns an empty table which is expected
pd.merge(left,right,left_index=True,right_index=True,left_on='key1')# it makes error !!!
答案 0 :(得分:1)
你有几个问题正在发生。首先,您的合并语句未正确构造。您不应同时使用left_on
和left_index
或right_on
和right_index
。您应该只使用一个左选项和一个右选项。
您在第二个语句中出错的原因是索引级别不匹配。在左侧合并中,左侧索引是单个级别,当您同时指定right_index=True
和right_on='event1'
时,right_on
属性优先。由于两者都是单级整数,所以没有问题。我应该指出合并,如果构造正确,(pd.merge(left, right, left_index=True, right_on='event1', how='left')
)不会产生空的DataFrame ...请参阅下面的代码。
在右侧合并中,您使用right_index=True
指定正确的索引,left_on
优先于left_index=True
。这里的问题是正确的索引是2级,其中' key1`字段是单级字符串。
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: right = pd.DataFrame(data=np.arange(12).reshape((6,2)),index=[['Nevada', 'Nevada', 'Ohio', 'Ohio', 'Ohio', 'Ohio'],[2001, 2000, 2000, 2000, 2001, 2002]],columns=['event1','event2'])
In [4]: left = pd.DataFrame(data={'key1':['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],'key2':[2000, 2001, 2002, 2001, 2002],'data':np.arange(5.)})
In [5]: left
Out[5]:
data key1 key2
0 0 Ohio 2000
1 1 Ohio 2001
2 2 Ohio 2002
3 3 Nevada 2001
4 4 Nevada 2002
In [6]: right
Out[6]:
event1 event2
Nevada 2001 0 1
2000 2 3
Ohio 2000 4 5
2000 6 7
2001 8 9
2002 10 11
In [5]: left_merge = left.merge(right, left_index=True, right_on='event1', how='left')
In [7]: left_merge
Out[7]:
data key1 key2 event1 event2
Nevada 2001 0 Ohio 2000 0 1
Ohio 2002 1 Ohio 2001 1 NaN
Nevada 2000 2 Ohio 2002 2 3
Ohio 2002 3 Nevada 2001 3 NaN
2000 4 Nevada 2002 4 5