w3resource

Pandas - Apply Different Functions on DataFrame Columns with apply()


Pandas: Custom Function Exercise-5 with Solution


Write a Pandas program that applies different functions on DataFrame columns using apply().

Apply different functions to different columns of a DataFrame by passing a dictionary to apply().

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 different custom functions
def add_one(x):
    return x + 1

def multiply_by_two(x):
    return x * 2

# Apply different functions to columns
df['A'] = df['A'].apply(add_one)
df['B'] = df['B'].apply(multiply_by_two)

# Output the result
print(df)

Output:

   A   B  C
0  2   8  7
1  3  10  8
2  4  12  9                               

Explanation:

  • Created a DataFrame with columns 'A', 'B', 'C'.
  • Defined two functions: add_one() and multiply_by_two().
  • Applied add_one() to column 'A' and multiply_by_two() to column 'B'.
  • Displayed the modified DataFrame.

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.