0

I created a function to take a column of a string datatype and ensure the first item in the string is always capitalized. Here is my function:

def myfunc(df, col):
     transformed_df = df[col][0].capitalize() + df[col][1:]
     return transformed_df

Using my function in my column of interest in my pandas dataframe:

df["mycol"].apply(myfunc)

I don't know why I get this error: TypeError: myfunc() missing 1 required positional argument: 'col'

Even adding axis to indicate that it should treat it column wise. I believe I am already passing my arguments why do I still need to specify col again? Correct me if I am wrong?

Your input is highly appreciated

1 Answer 1

1

If use Series.apply then each value of Series is processing separately, so need:

def myfunc(val):
     return val[0].capitalize() + val[1:]

If want use pandas strings functions:

df["mycol"].str[0].str.capitalize() + df["mycol"].str[1:]

If want pass to function:

def myfunc(col):
    return col.str[0].str.capitalize() + col.str[1:]

Then use Series.pipe for processing Series:

df["mycol"].pipe(myfunc)

Or:

myfunc(df["mycol"])
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! Thanks for the insights. Silly me.

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.