Pandas Series.apply()
Pandas Series.apply() Tutorial
In this tutorial, we'll explore the Series.apply() method in Pandas, which is used to apply a function along the axis of a Pandas Series, with well detailed example programs.
The syntax of Series.apply(func, convert_dtype=True, args=(), **kwds) is:
Series.apply(func, convert_dtype=True, args=(), **kwds)where
| Parameter | Description |
|---|---|
func | The function to apply to each element in the Series. |
convert_dtype | If True, infer the datatype of the result to be the same as the input Series. Default is True. |
args | Additional arguments to pass to the function func. |
**kwds | Additional keyword arguments to pass to the function func. |
The Series.apply() method applies the function func to each element in the Series and returns a new Series with the results.
Examples for Pandas Series.apply() function
1. Apply a custom function to double each element in the Series
In this example, we'll take a series of integer values in int_series variable, and use Series.apply() to apply a custom function that doubles each element in the int_series.
Python Program
import pandas as pd
# Create a series
series = pd.Series([10, 20, 30, 40, 50])
# Define a custom function to double each element
def double_element(x):
return x * 2
# Apply the custom function using apply()
result = series.apply(double_element)
# Print original series and result
print("Original Series:")
print(series)
print("\nAfter applying the function:")
print(result)Output
Original Series:
0 10
1 20
2 30
3 40
4 50
dtype: int64
After applying the function:
0 20
1 40
2 60
3 80
4 100
dtype: int642. Apply a lambda function to square each element in the series
In this example, we'll use Series.apply() to apply a lambda function that squares each element in the given Series.
Python Program
import pandas as pd
# Create a series
series = pd.Series([10, 20, 30, 40, 50])
# Apply the custom function using apply()
result = series.apply(lambda x: x**2)
# Print original series and result
print("Original Series:")
print(series)
print("\nAfter applying the function:")
print(result)Output
Original Series:
0 10
1 20
2 30
3 40
4 50
dtype: int64
After applying the function:
0 100
1 400
2 900
3 1600
4 2500
dtype: int64Summary
In this tutorial, we've covered the Series.apply() method in Pandas, which allows you to apply a function to each element in a Series.