How to Use Pandas apply() inplace


The pandas apply() function can be used to apply a function across rows or columns of a pandas DataFrame.

This function is different from other functions like drop() and replace() that provide an inplace argument:

df.drop(['column1'], inplace=True)

df.rename({'old_column' : 'new_column'}, inplace=True)

The apply() function has no inplace argument, so we must use the following syntax to transform a DataFrame inplace:

df = df.apply(lambda x: x*2)

The following examples show how to use this syntax in practice with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
df

        points	assists	 rebounds
0	25	5	 11
1	12	7	 8
2	15	7	 10
3	14	9	 6
4	19	12	 6
5	23	9	 5
6	25	9	 9
7	29	4	 12

Example 1: Use apply() inplace for One Column

The following code shows how to use apply() to transform one data frame column inplace:

#multiply all values in 'points' column by 2 inplace
df.loc[:, 'points'] = df.points.apply(lambda x: x*2)

#view updated DataFrame
df

points	assists	rebounds
0	50	5	11
1	24	7	8
2	30	7	10
3	28	9	6
4	38	12	6
5	46	9	5
6	50	9	9
7	58	4	12

Example 2: Use apply() inplace for Multiple Columns

The following code shows how to use apply() to transform multiple data frame columns inplace:

multiply all values in 'points' and 'rebounds' column by 2 inplace
df[['points', 'rebounds']] = df[['points', 'rebounds']].apply(lambda x: x*2)

#view updated DataFrame
df

	points	assists	rebounds
0	50	5	22
1	24	7	16
2	30	7	20
3	28	9	12
4	38	12	12
5	46	9	10
6	50	9	18
7	58	4	24

Example 3: Use apply() inplace for All Columns

The following code shows how to use apply() to transform all data frame columns inplace:

#multiply values in all columns by 2
df = df.apply(lambda x: x*2)

#view updated DataFrame
df

	points	assists	rebounds
0	50	10	22
1	24	14	16
2	30	14	20
3	28	18	12
4	38	24	12
5	46	18	10
6	50	18	18
7	58	8	24

Additional Resources

The following tutorials explain how to perform other common functions in pandas:

How to Calculate the Sum of Columns in Pandas
How to Calculate the Mean of Columns in Pandas
How to Find the Max Value of Columns in Pandas

Leave a Reply

Your email address will not be published.