w3resource

Pandas - Applying Custom Function to Modify Data Based on Column Types

Pandas: Custom Function Exercise-11 with Solution

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.

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://198.211.115.131/python-exercises/pandas/pandas-apply-custom-function-to-modify-dataframe-based-on-column-types.php