Python Pandas:DataFrame.apply(f,axis=1)在空数据帧上忽略异常?

Python Pandas:DataFrame.apply(f,axis=1)在空数据帧上忽略异常?,python,pandas,Python,Pandas,如果应用于空数据帧的函数引发异常,则为空 返回数据帧: >>> import pandas as pd >>> def raise_exc(*a, **kw): ... raise Exception() ... >>> empty = pd.DataFrame({"a": []}) >>> empty.apply(raise_exc, index=1) Empty DataFrame Columns: [a] Ind

如果应用于空数据帧的函数引发异常,则为空 返回数据帧:

>>> import pandas as pd
>>> def raise_exc(*a, **kw):
...   raise Exception()
... 
>>> empty = pd.DataFrame({"a": []})
>>> empty.apply(raise_exc, index=1)
Empty DataFrame
Columns: [a]
Index: []

为什么会这样?与重新引发异常(数据帧不为空时的情况)或返回序列(正常情况下)相反,它返回空数据帧有什么原因吗?

深入研究Pandas源代码,看起来这是罪魁祸首:

if not all(self.shape):
    # How to determine this better?
    is_reduction = False
    try:
        is_reduction = not isinstance(f(_EMPTY_SERIES), Series)
    except Exception:
        pass

    if is_reduction:
        return Series(NA, index=self._get_agg_axis(axis))
    else:
        return self.copy()
因此,事实上,Pandas正试图聪明地猜测它是否应该返回一个
数据帧
或一个
系列
,例外情况是抛出一些东西


我想应该有一个补丁。

可能只是一个没有测试的边缘案例。