gpt4 book ai didi

python - Python 中 try-catch-raise 异常子句的两次运行行为

转载 作者:太空宇宙 更新时间:2023-11-04 10:07:27 26 4
gpt4 key购买 nike

在下面的最小示例中,我用我自己的方法 safe_apply 包装了 pandas.DataFrame.apply 方法。此方法在两个方面不同于普通的 apply:

  1. 它不是在 NDFrame 中返回值,而是将它们附加到列表 results 中。
  2. 如果异常被捕获,results 会在错误出现和执行终止之前被打印出来。

代码如下:

from pandas.core.frame import DataFrame, Series
import pandas as pd

def safe_apply(df, func, **kwargs):
results = []

def new_func(srs):
try:
results.append(func(srs))
except Exception as e:
print(results)
raise

df.apply(new_func, **kwargs)
return results

DataFrame.safe_apply = safe_apply

def f(srs):
if (pd.notnull(srs['lat'])) & (pd.notnull(srs['long'])):
return srs['lat'] + srs['long']
else:
raise ValueError


ex = pd.DataFrame({'lat': [1, 2, None], 'long': [1, 2, None]}, index=['A', 'B', 'C'])
ex.safe_apply(f, axis='columns')

当我执行这个时,我除了将函数 f 应用于 ex 的前两行然后在第三行失败的结果:a print 来自 [2.0, 4.0],后跟 ValueError

相反,我得到了一个ValueError两行 输出:

[2.0, 4.0]
[2.0, 4.0, 2.0, 4.0]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-1-382c07ef0919> in <module>()
26 raise ValueError
27
---> 28 ex.safe_apply(f, axis='columns')

<ipython-input-1-382c07ef0919> in safe_apply(df, func, **kwargs)
12 raise
13
---> 14 df.apply(new_func, **kwargs)
15
16 return results

C:\Users\Alex\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
4059 if reduce is None:
4060 reduce = True
-> 4061 return self._apply_standard(f, axis, reduce=reduce)
4062 else:
4063 return self._apply_broadcast(f, axis)

C:\Users\Alex\Anaconda3\lib\site-packages\pandas\core\frame.py in _apply_standard(self, func, axis, ignore_failures, reduce)
4155 try:
4156 for i, v in enumerate(series_gen):
-> 4157 results[i] = func(v)
4158 keys.append(v.name)
4159 except Exception as e:

<ipython-input-1-382c07ef0919> in new_func(srs)
7 def new_func(srs):
8 try:
----> 9 results.append(func(srs))
10 except Exception as e:
11 print(results)

<ipython-input-1-382c07ef0919> in f(srs)
24 return srs['lat'] + srs['long']
25 else:
---> 26 raise ValueError
27
28 ex.safe_apply(f, axis='columns')

ValueError: occurred at index C

意思是代码到达异常子句,打印出结果,然后再次运行该函数而不是抛出错误并停止,以某种方式再次运行该函数(?)。

为什么会这样?

最佳答案

请参阅 docstring 上的注释部分, 具体来说

In the current implementation apply calls func twice on the first column/row to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if func has side-effects, as they will take effect twice for the first column/row.

关于python - Python 中 try-catch-raise 异常子句的两次运行行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40293504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com