2
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
  • 2
    You need to pass to apply the function to use, but instead you're calling shorterstring yourself. Try df["A"].apply(lambda s : shorterstring(s, 2)) (the lambda is still there to reduce your `shorterstring``to a single-parameter function. You could also use functool.partial for that Commented Oct 23, 2019 at 10:03

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.