如何在try-except语句中使用MergeError?

时间:2018-12-29 05:59:06

标签: python pandas merge

我正在编写一个用于合并表1-1的程序,并且想要在validate ='一对一'不起作用时通过try-except语句使用concat。

但是,我未能在“ MergeError除外,例如e”代码中使用MergeError。

由于我正在编写的实际代码太长,因此我举了一个简单的例子来说明我的问题。在下面的代码中,如果我使用

result = pd.merge(left,right,on ='B',how ='outer',validate =“ one_to_one”)

,它将返回MergeError。

但是,对于try-except代码,它无法处理MergeError情况。它返回另一个错误,名为NameError。

是否有任何方法可以处理MergeError?

import pandas as pd

left = pd.DataFrame({'A' : [1,2], 'B' : [1, 2]})
right = pd.DataFrame({'A' : [4,5,6], 'B': [2, 2, 2]})

try:
    result = pd.merge(left, right, on='B', how='outer', validate="one_to_one")
except MergeError as e:
    print("ok ",e)





MergeError                                Traceback (most recent call last)
<ipython-input-1-2a4c90911337> in <module>()
      6 try:
----> 7     result = pd.merge(left, right, on='B', how='outer', 
validate="one_to_one")
      8 except MergeError as e:

~\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py in merge(left, 
right, how, on, left_on, right_on, left_index, right_index, sort, suffixes, 
copy, indicator, validate)
     59                          copy=copy, indicator=indicator,
---> 60                          validate=validate)
     61     return op.get_result()

~\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py in 
__init__(self, left, right, how, on, left_on, right_on, axis, left_index, 
right_index, sort, suffixes, copy, indicator, validate)
    559         if validate is not None:
--> 560             self._validate(validate)
    561 

~\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py in 
_validate(self, validate)
   1079             elif not right_unique:
-> 1080                 raise MergeError("Merge keys are not unique in 
right dataset;"
   1081                                  " not a one-to-one merge")

MergeError: Merge keys are not unique in right dataset; not a one-to-one 
merge

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-1-2a4c90911337> in <module>()
      6 try:
      7     result = pd.merge(left, right, on='B', how='outer', validate="one_to_one")
----> 8 except MergeError as e:
      9     print("ok ",e)

NameError: name 'MergeError' is not defined

2 个答案:

答案 0 :(得分:1)

使用此:

except pd.errors.MergeError as e:

或者,也可以在顶部导入名称:

from pd.errors import MergeError

答案 1 :(得分:0)

您需要先从其包含的模块导入MergeError,然后才能按名称进行捕获。

from pandas.errors import MergeError