Pandas apply runs extra time when return a series

Viewed 46

Below is my test code:

# coding: utf8

import pandas as pd

def main():

    df = pd.DataFrame({
        'name': ['AA', 'BB', 'CC'],
        'age': [23, 33, 29],
    })
    print('Pandas verson is', pd.__version__)
    print(df)

    print(' return tuple '.center(80, '='))
    df_out = df.apply(calc_discount, axis=1)
    print(df_out)

    print(' return series '.center(80, '='))
    df_out = df.apply(lambda row: pd.Series(calc_discount(row)), axis=1)
    print(df_out)    

def calc_discount(row):
    print('~~~ row ~~~')
    label = row['name'][0] + '_label'
    discount = row['age'] // 3
    return label, discount


if __name__ == '__main__': main()

And here's the result for your reference:

Pandas verson is 1.0.5
  name  age
0   AA   23
1   BB   33
2   CC   29
================================= return tuple =================================
~~~ row ~~~
~~~ row ~~~
~~~ row ~~~
0     (A_label, 7)
1    (B_label, 11)
2     (C_label, 9)
dtype: object
================================ return series =================================
~~~ row ~~~
~~~ row ~~~
~~~ row ~~~
~~~ row ~~~
         0   1
0  A_label   7
1  B_label  11
2  C_label   9

When the apply function returns a tuple, the calc_discount function is called 3 times as expected. but when I changed the return type, the function call becomes a little strange.

Any idea why the apply executes extra one more time when it returns a pd.Series?

Thank you very much~

0 Answers
Related