Series.apply() method in Pandas is used to apply a function to each element of a Series. It allows to transform, modify or categorize data easily by running a custom function or lambda function on every value.
Example: This example applies a function to double each value in a Series.
import pandas as pd
s = pd.Series([1, 2, 3, 4])
r = s.apply(lambda x: x * 2)
print(r)
Output
0 2 1 4 2 6 3 8 dtype: int64
Explanation: s.apply(lambda x: x * 2) applies the function to each element of s and each value is multiplied by 2 and returned as a new Series
Syntax
Series.apply(func, convert_dtype=True, args=())
Parameters:
- func: Function to apply on each value of the Series
- convert_dtype: Converts result to best possible dtype (default True)
- args: Additional arguments passed to the function
Return: Returns a new Pandas Series with modified values
Examples
Example 1: This example uses apply() with a custom function to classify each mark in the Series as Pass or Fail based on a condition.
import pandas as pd
s = pd.Series([35, 67, 90, 45])
def f(x):
return "Pass" if x >= 50 else "Fail"
r = s.apply(f)
print(r)
Output
0 Fail 1 Pass 2 Pass 3 Fail dtype: object
Explanation:
- pd.Series([35, 67, 90, 45]) creates a Series of marks.
- def f(x): defines a function that checks each value.
- "Pass" if x >= 50 else "Fail" returns result based on condition.
- s.apply(f) applies function f to every element of the Series.
Example 2: This example uses apply() with a lambda function to increase each salary value in the Series by 10%.
import pandas as pd
s = pd.Series([10000, 15000, 20000])
r = s.apply(lambda x: x * 1.10)
print(r)
Output
0 11000.0 1 16500.0 2 22000.0 dtype: float64
Explanation:
- lambda x: x * 1.10 defines a function to increase value by 10%.
- s.apply(lambda x: x * 1.10) applies this function to each salary.
- Each value is multiplied by 1.10.
Example 3: This example uses apply() to convert each numeric value into a formatted text string.
import pandas as pd
s = pd.Series([5, 10, 15])
r = s.apply(lambda x: "Value is " + str(x))
print(r)
Output
0 Value is 5 1 Value is 10 2 Value is 15 dtype: object
Explanation:
- lambda x: "Value is " + str(x) converts number into text.
- str(x) converts numeric value into string.
- s.apply(...) applies this conversion to every element.