Skip to content

like old issue #2936: df.apply(foo) will run twice at the first row #30815

Closed
@kerwin6182828

Description

@kerwin6182828
- :meth:`DataFrame.apply` and :meth:`DataFrame.applymap` now evaluates first row/column only once (:issue:`31620`, :issue:`30815`, :issue:`33879`).

.. ipython:: python

    df = pd.DataFrame({'a': [1, 2], 'b': [3, 6]})

    def func(row):
        print(row)
        return row

*Previous behavior*:

.. code-block:: ipython

    In [4]: df.apply(func, axis=1)
    a    1
    b    3
    Name: 0, dtype: int64
    a    1
    b    3
    Name: 0, dtype: int64
    a    2
    b    6
    Name: 1, dtype: int64
    Out[4]:
       a  b
    0  1  3
    1  2  6

*New behavior*:

.. ipython:: python

    df.apply(func, axis=1)

some example....

def foo(row):
    status = row.get("status")
    print(status)
    status = True if status==1 else False
    row["status"] = status
    return row
    
df = pd.DataFrame([{"name":"bob", "status":1}])
df.apply(foo, axis=1)

>>>>>>>> output:
1
True

Problem description

today, I have a problem that df.apply(foo) will run twice at the first row like old issue #2936.
I read a lot of explanations, but still can't find some help. As I wrote above, when df just have 1 row and then apply function will run twice at this row lead to print diffierent values.
(It just modified my original value "1" to "True", but it confused me a lot...)

I am wandering how to handle this issue, and is this a pandas bug?

thanks a lot~~

Metadata

Metadata

Assignees

No one assigned

    Labels

    ApplyApply, Aggregate, Transform, Map

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions