Apply function Pandas DataFrame without Lambda paramater

Viewed 59
df = pd.DataFrame([["Test", "Test123"]] * 3, columns=['A', 'B'])


def shorterstring(string, count): 
    return string[0:-count]


df["A"].apply(lambda x: x[0:2])
Out[614]: 
0    Te
1    Te
2    Te

df["A"].apply(shorterstring(df["A"], 2))
TypeError: 'Series' object is not callable

I want to apply a custom function on a column with strings. I managed to get this to work with the lambda expression, but when I want to apply the function it does not work. Can anyone help me how to do this?

1 Answers

With functools.partial feature:

In [128]: from functools import partial                                                                     

In [129]: df["A"].apply(partial(shorterstring, count=2))                                                    
Out[129]: 
0    Te
1    Te
2    Te
Name: A, dtype: object
Related