python-3.xpandasfunction

Cannot understand why pd.Series.map fails with a lambda function


Say I have a panda series

import pandas as pd
s = ["A", "b"], ["c", "e"]
test_series = pd.Series(data=s)
0    [A, b]
1    [c, e]
dtype: object

and then do

test_series.map('|'.join)

and output

0    A|b
1    c|e
dtype: object

but when I try using a lambda function (wrongly assuming it would yield the same output)

test_series.map(lambda x: '|'.join)

get output

0    <built-in method join of str object at 0x10bc4...
1    <built-in method join of str object at 0x10bc4...
dtype: object

I guess it is related to the fact type(lambda x: '|'.join) gives function, while

type('|'.join)

gives builtin_function_or_method

but I do not understand the details.


Solution

  • Well, lambda x: '|'.join is a function that takes a parameter x, ignores it and returns a function/method.

    What you would need is to call the function with your parameter:

    test_series.map(lambda x: '|'.join(x))
    

    Since this is a useless use of lambda, it is much better to go with:

    test_series.map('|'.join)
    

    I guess it is related to the fact type(lambda x: '|'.join) gives function, while type('|'.join) gives builtin_function_or_method

    Not quite, you would need to compare:

    type((lambda x: '|'.join)(['a', 'b']))
    # builtin_function_or_method
    
    type('|'.join(['a', 'b']))
    # str