我当时正在编写一个用于合并表1-1的程序,并且想通过try-except语句使用concat,如果validate ='一对一'不起作用。
但是,我无法在“ MergeError除外,例如e:”代码中使用MergeError。
由于我正在编写的实际代码太长,因此我举了一个简单的例子来说明我的问题。在下面的代码中,如果我使用
结果= pd.merge(左,右,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
最佳答案
您需要从其包含的模块导入MergeError
,然后才能按名称捕获它。
from pandas.errors import MergeError
关于python - 如何在try-except语句中使用MergeError?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53967109/