w3resource

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


Pandas: Custom Function Exercise-6 with Solution


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.

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.