w3resource

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


5. Apply Different Functions on DataFrame Columns Using apply()

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to apply the mean function on numeric columns and the mode on non-numeric columns using apply() with a custom lambda.
  • Write a Pandas program to apply multiple aggregation functions to different columns by passing a dictionary to apply().
  • Write a Pandas program to compute the range for one column and the median for another by selectively applying functions using apply().
  • Write a Pandas program to use apply() to apply a different transformation to each column based on its data type.

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.