33
You can use the following syntax to apply a function to one or more columns of a pandas DataFame:
#divide values in column1 by 2 df['column1'] = df['column1'] / 2 #divide values in column1 and column2 by 2 df[['column1', 'column2']] = df[['column1', 'column2']] / 2 #divide values in every column of DataFrame by 2 df = df / 2
The following examples show how to use this syntax in practice.
Example 1: Apply Function to One Column
The following code shows how to apply a function to just one column of a DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'points': [10, 12, 12, 14, 13, 18], 'rebounds': [7, 7, 8, 13, 7, 4], 'assists': [11, 8, 10, 6, 6, 5]}) #view DataFrame df points rebounds assists 0 10 7 11 1 12 7 8 2 12 8 10 3 14 13 6 4 13 7 6 5 18 4 5 #divide values in points column by 2 df['points'] = df['points'] / 2 #view updated DataFrame df points rebounds assists 0 5.0 7 11 1 6.0 7 8 2 6.0 8 10 3 7.0 13 6 4 6.5 7 6 5 9.0 4 5
Example 2: Apply Function to Specific Columns
The following code shows how to apply a function to specific columns of a DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'points': [10, 12, 12, 14, 13, 18], 'rebounds': [7, 7, 8, 13, 7, 4], 'assists': [11, 8, 10, 6, 6, 5]}) #view DataFrame df points rebounds assists 0 10 7 11 1 12 7 8 2 12 8 10 3 14 13 6 4 13 7 6 5 18 4 5 #divide values in points and rebounds column by 2 df[['points', 'rebounds']] = df[['points', 'rebounds']] / 2 #view updated DataFrame df points rebounds assists 0 5.0 3.5 11 1 6.0 3.5 8 2 6.0 4.0 10 3 7.0 6.5 6 4 6.5 3.5 6 5 9.0 2.0 5
Example 3: Apply Function to All Columns
The following code shows how to apply a function to every column of a DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'points': [10, 12, 12, 14, 13, 18], 'rebounds': [7, 7, 8, 13, 7, 4], 'assists': [11, 8, 10, 6, 6, 5]}) #view DataFrame df points rebounds assists 0 10 7 11 1 12 7 8 2 12 8 10 3 14 13 6 4 13 7 6 5 18 4 5 #divide values in every column by 2 df = df / 2 #view updated DataFrame df points rebounds assists 0 5.0 3.5 5.5 1 6.0 3.5 4.0 2 6.0 4.0 5.0 3 7.0 6.5 3.0 4 6.5 3.5 3.0 5 9.0 2.0 2.5
Additional Resources
How to Calculate the Mean of Columns in Pandas
How to Calculate the Sum of Columns in Pandas
How to Find the Max Value of Columns in Pandas