w3resource

Pandas - Apply a Lambda Function to Column Values with apply()


6. Apply Lambda Function to DataFrame Columns Using apply()

Write a Pandas program that apply a Lambda function to DataFrame columns using apply() function.

In this exercise, we have applied a lambda function that halves the values of a column using apply() function.

Sample Solution:

Code :

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({
    'A': [10, 20, 30],
    'B': [40, 50, 60]
})

# Apply a lambda function to halve the values in column 'A'
df['A'] = df['A'].apply(lambda x: x / 2)

# Output the result
print(df)

Output:

      A   B
0   5.0  40
1  10.0  50
2  15.0  60                               

Explanation:

  • Created a DataFrame with columns 'A' and 'B'.
  • Applied a lambda function to divide the values in column 'A' by 2.
  • Modified column 'A' and printed the updated DataFrame.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to apply a lambda function on a column that calculates the percentage change from the previous row using apply().
  • Write a Pandas program to use apply() with a lambda function to convert temperature values from Celsius to Fahrenheit in a DataFrame column.
  • Write a Pandas program to apply a lambda function to each column that rounds numeric values to the nearest integer using apply().
  • Write a Pandas program to use apply() with a lambda function to flag values above a threshold in a DataFrame column.

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.