Examples
Create a series with typical summer temperatures for each city.
import numpy as np
import pandas as pd
s = pd.Series([31, 27, 11],
index=['Beijing', 'Los Angeles', 'Berlin'])
s
Square the values by defining a function and passing it as an argument to apply().
def square(x):
return x ** 2
s.apply(square)
Square the values by passing an anonymous function as an argument to apply().
s.apply(lambda x: x ** 2)
Define a custom function that needs additional positional arguments and pass these additional arguments
using the args keyword.
def subtract_custom_value(x, custom_value):
return x - custom_value
s.apply(subtract_custom_value, args=(4,))
Define a custom function that takes keyword arguments and pass these arguments to apply.
def add_custom_values(x, **kwargs):
for month in kwargs:
x += kwargs[month]
return x
s.apply(add_custom_values, november=18, december=16, january=15)
Use a function from the Numpy library.
s.apply(np.log)