w3resource

Pandas - Applying a Custom Function Element-wise with applymap()


1. Apply Custom Function Element-wise with applymap()

Write a Pandas program that apply a custom function element-wise using applymap() function.

In this exercise, we have applied a custom function that squares each element of a Pandas DataFrame element-wise using applymap().

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 square each element
def square(x):
    return x ** 2

# Apply the custom function element-wise using applymap()
df_squared = df.applymap(square)

# Output the result
print(df_squared)

Output:

   A   B   C
0  1  16  49
1  4  25  64
2  9  36  81                                      

Explanation:

  • Created a DataFrame with columns 'A', 'B', 'C'.
  • Defined a function square() that squares its input.
  • Applied the square() function to each element of the DataFrame using applymap().
  • Displayed the resulting DataFrame where each element has been squared.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to apply a custom function element-wise using applymap() that multiplies each numeric value by 2.
  • Write a Pandas program to use applymap() to convert all string entries in a DataFrame to uppercase.
  • Write a Pandas program to apply a custom lambda function using applymap() that replaces negative numbers with zero.
  • Write a Pandas program to use applymap() on a DataFrame to format float numbers to 2 decimal places.

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.



Follow us on Facebook and Twitter for latest update.