zoukankan      html  css  js  c++  java
  • 【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
    
  • 相关阅读:
    实验四 交换机的Telnet远程登陆配置
    实验三 交换机的基本配置与管理
    实验二 认识Packet Tracer软件
    实验一 网络连接线的制作
    python入门(七)
    python入门(六)
    python入门(五)
    Android练习(二)
    Android练习(一)
    python入门(四)
  • 原文地址:https://www.cnblogs.com/XD00/p/12258592.html
Copyright © 2011-2022 走看看