Can you use apply() in Pandas to update in-place?

Question

Can we utilize the apply() method in Pandas to update a dataframe in-place?

Answer

No, unlike other methods that update the dataframe for which you can specify in-place, such as

df.drop(['A'], inplace=True)
df.rename({'B' : 'C'}, inplace=True)

using the apply() method does not have the parameter for inplace.

As a result, whenever you use apply() on a dataframe, if you wish to update the dataframe, then you must reassign it, for example:

df = df.apply(my_lambda)

5 Likes

So there is no way that a function like df[‘Name’] = df.name.apply(lower) could work?

1 Like

You have to manually re-assign the values to the columns/features that you are applying the lambda function to.
df[[‘col1’, ‘col2’]] = df[[‘col1’, ‘col2’]].apply(lambda)

PS:I was trying to do something similar with iloc instead of specifying the column names explicitly and the apply wasn’t working, because it was returning a copy image of the data set.

This is explicitly was the ‘upper’ example did. It worked because you re-assigned the values in 'Name" with the new apply(upper) values.

The difference is you are re-assigning when you use the equal sign. The ‘inplace’ is not re-assigning, but is modifying the existing data.

image

6 Likes

What is the recommended way to work with strings in a Series or DataFrame through .str or through .apply( )

df[“column”].str.lower()

or

df[“column”].apply(lower)

I posted about it in another topic:

The lower is one of the deprecated string functions in Python 2, and in Python 3, it is removed from the string library. So importing lower from string library is no longer recommended. It is recommended to use str.lower instead.

df["column"].str.lower() is a way using the str.lower method of Pandas Series object. As a way along with this exercise that uses the .apply() method, we can also simply replace lower with str.lower as a Python built-in string method (or this, in Python 3): df["column"].apply(str.lower). In either case, from string import lower on the line 2 is no longer needed.

4 Likes