w3resource

Pandas - Applying a Custom Function to Columns using apply()

Pandas: Custom Function Exercise-3 with Solution

Write a Pandas program that apply a custom function to each column using apply() function.

In this exercise, we have applied a custom function to calculate the mean of each column using apply() column-wise.

Sample Solution:

Code :

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6],
    'C': [7, 8, 9]
})

# Define a custom function to calculate the mean of a column
def column_mean(column):
    return column.mean()

# Apply the custom function column-wise to calculate the mean of each column
means = df.apply(column_mean, axis=0)

# Add the means as a new row to the DataFrame
df.loc['Mean'] = means

# Output the result
print(df) 

Output:

        A    B    C
0     1.0  4.0  7.0
1     2.0  5.0  8.0
2     3.0  6.0  9.0
Mean  2.0  5.0  8.0                                    

Explanation:

  • Create a DataFrame: The sample DataFrame is created with columns 'A', 'B', and 'C', each containing 3 numerical values.
  • Define Custom Function: The column_mean function is defined to calculate the mean of a column using column.mean().
  • Apply Function to Columns: The apply() function is used with axis=0 to apply column_mean to each column of the DataFrame, calculating the mean of each column.
  • Add Means as a Row: The calculated column means are added as a new row labeled 'Mean' using df.loc['Mean'].

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/pandas-apply-custom-functions-to-columns-in-dataframe-using-apply.php