【python pandas】对空的DataFrame使用apply函数,返回DataFrame类型

报错信息

ValueError: Wrong number of items passed 13, placement implies 1

解决方案

首先需要判明pandas的版本是什么,不同的版本拥有不同的解决方案,或者直接去看本地pandas源码中的对于参数的解释也可以。因为在最开始的时候,我直接去百度搜索pandas apply,其实前面几个都是旧版本的,根据旧版本的可能会出现错误。

apply中有一个参数是reduce,文档如下。它的作用就是,当DataFrame为空的时候,使用reduce来确定返回的类型。
1. None 默认,让pandas直接去猜
2. True,总是返回Series
3. False,总时返回DataFrame
注意:在0.23.0版本后,要需要让result_type='reduce'才能生效。(所以我说要看不同版本各自的文档)

reduce : bool or None, default None
            Try to apply reduction procedures. If the DataFrame is empty,
            `apply` will use `reduce` to determine whether the result
            should be a Series or a DataFrame. If ``reduce=None`` (the
            default), `apply`'s return value will be guessed by calling
            `func` on an empty Series
            (note: while guessing, exceptions raised by `func` will be
            ignored).
            If ``reduce=True`` a Series will always be returned, and if
            ``reduce=False`` a DataFrame will always be returned.

            .. deprecated:: 0.23.0
               This argument will be removed in a future version, replaced
               by ``result_type='reduce'``.

实例


对于第一种,如果把他当作一列就肯定会报错了。

更新

在更加新的版本中直接使用result='reduce'即可

result_type : {'expand', 'reduce', 'broadcast', None}, default None
            These only act when ``axis=1`` (columns):

            * 'expand' : list-like results will be turned into columns.
            * 'reduce' : returns a Series if possible rather than expanding
              list-like results. This is the opposite of 'expand'.
            * 'broadcast' : results will be broadcast to the original shape
              of the DataFrame, the original index and columns will be
              retained.

            The default behaviour (None) depends on the return value of the
            applied function: list-like results will be returned as a Series
            of those. However if the apply function returns a Series these
            are expanded to columns.

            .. versionadded:: 0.23.0
posted @ 2020-02-04 10:49  丿小呆  阅读(2827)  评论(0编辑  收藏  举报