Pandas - Applying Custom Function to Modify Data Based on Column Types
11. Custom Function to Modify Data Based on Column Types
Write a Pandas program to create a custom function to modify data based on column types.
This exercise shows how to apply different operations on columns based on their data types using apply().
Sample Solution:
Code :
import pandas as pd
# Create a sample DataFrame with mixed data types
df = pd.DataFrame({
'A': [1, 2, 3],
'B': ['x', 'y', 'z'],
'C': [1.1, 2.2, 3.3]
})
# Define a custom function to modify data based on type
def modify_based_on_type(x):
if isinstance(x, int):
return x + 10 # Add 10 if integer
elif isinstance(x, float):
return x * 2 # Double if float
else:
return x.upper() # Uppercase if string
# Apply the function to each element using applymap()
df_modified = df.applymap(modify_based_on_type)
# Output the result
print(df_modified)
Output:
A B C 0 11 X 2.2 1 12 Y 4.4 2 13 Z 6.6
Explanation:
- Created a DataFrame with integer, string, and float columns.
- Defined a function modify_based_on_type() that modifies data based on its type:
- Adds 10 to integers.
- Doubles floats.
- Converts strings to uppercase.
- Applied the function to each element in the DataFrame using applymap().
- Displayed the updated DataFrame with modified values.
For more Practice: Solve these Related Problems:
- Write a Pandas program to apply a custom function that modifies numeric columns by scaling them and converts object columns to lowercase.
- Write a Pandas program to create a function that checks the data type of each column and applies an appropriate transformation using apply().
- Write a Pandas program to modify a DataFrame by applying different functions based on the column type, then output the transformed DataFrame.
- Write a Pandas program to use apply() with a custom function that normalizes numeric columns and formats date columns.
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.