微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – Pandas:为什么DataFrame.apply(f,axis = 1)在DataFrame为空时调用f?

为什么Pandas的DataFrame.apply方法在DataFrame为空时调用正在应用的函数

例如:

>>> import pandas as pd
>>> df = pd.DataFrame({"foo": []})
>>> df
Empty DataFrame
Columns: [foo]
Index: []
>>> x = []
>>> df.apply(x.append, axis=1)
Series([], dtype: float64)
>>> x
[Series([], dtype: float64)] # <<< why was the apply callback called with an empty row?

解决方法:

深入挖掘熊猫来源,看起来这就是罪魁祸首:

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正在调用没有参数的函数,试图猜测结果应该是Series还是DataFrame.

我想补丁是有序的.

编辑:此问题已修补,现在已记录在案,并允许使用reduce选项来避免它:http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐