Examples

In [1]:
import numpy as np
import pandas as pd
In [2]:
df = pd.DataFrame([[9, 25]] * 3, columns=['P', 'Q'])
df
Out[2]:
P Q
0 9 25
1 9 25
2 9 25

Pandas: DataFrame - apply.

Using a numpy universal function (in this case the same as np.sqrt(df)):

In [3]:
df.apply(np.sqrt)
Out[3]:
P Q
0 3.0 5.0
1 3.0 5.0
2 3.0 5.0

Pandas: DataFrame - Using a numpy universal function (in this case the same as np.sqrt(df)).

Using a reducing function on either axis

In [4]:
df.apply(np.sum, axis=0)
Out[4]:
P    27
Q    75
dtype: int64

Pandas: DataFrame - Using a reducing function on either axis 0.

In [5]:
df.apply(np.sum, axis=1)
Out[5]:
0    34
1    34
2    34
dtype: int64

Pandas: DataFrame - Using a reducing function on either axis 1.

Returning a list-like will result in a Series:

In [6]:
df.apply(lambda x: [1, 2], axis=1)
Out[6]:
0    [1, 2]
1    [1, 2]
2    [1, 2]
dtype: object

Passing result_type=’expand’ will expand list-like results to columns of a Dataframe:

In [7]:
df.apply(lambda x: [1, 2], axis=1, result_type='expand')
Out[7]:
0 1
0 1 2
1 1 2
2 1 2

Returning a Series inside the function is similar to passing result_type='expand'.
The resulting column names will be the Series index.

In [8]:
df.apply(lambda x: pd.Series([1, 2], index=['f1', 'b1']), axis=1)
Out[8]:
f1 b1
0 1 2
1 1 2
2 1 2

Passing result_type='broadcast' will ensure the same shape result, whether list-like
or scalar is returned by the function, and broadcast it along the axis. The resulting
column names will be the originals.

In [9]:
df.apply(lambda x: [1, 2], axis=1, result_type='broadcast')
Out[9]:
P Q
0 1 2
1 1 2
2 1 2