Pandas - Applying a Custom Function Element-wise with applymap()
Pandas: Custom Function Exercise-1 with Solution
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.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics