Pandas provides an effective way to apply a function to every element of a Series and get a new Series. Let us assume we have the following Series:
>>> import pandas as pd
>>> s = pd.Series([3, 7, 5, 8, 9, 1, 0, 4])
>>> s
0 3
1 7
2 5
3 8
4 9
5 1
6 0
7 4
dtype: int64
and a square function:
>>> def square(x):
... return x*x
We can simply apply square to every element of s and get a new Series:
>>> t = s.apply(square)
>>> t
0 9
1 49
2 25
3 64
4 81
5 1
6 0
7 16
dtype: int64
In some cases it is easier to use a lambda expression:
>>> s.apply(lambda x: x ** 2)
0 9
1 49
2 25
3 64
4 81
5 1
6 0
7 16
dtype: int64
or we can use any builtin function:
>>> q = pd.Series(['Bob', 'Jack', 'Rose'])
>>> q.apply(str.lower)
0 bob
1 jack
2 rose
dtype: object
If all the elements of the Series are strings, there is an easier way to apply string methods:
>>> q.str.lower()
0 bob
1 jack
2 rose
dtype: object
>>> q.str.len()
0 3
1 4
2 4