NB: Method Chaining

Method chaining is supported by many objects in Python.

This allows you to “chain” a series of methods without having to defined temporary variables.

import numpy as np
import pandas as pd
import seaborn as sns
iris = sns.load_dataset('iris')
iris
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
... ... ... ... ... ...
145 6.7 3.0 5.2 2.3 virginica
146 6.3 2.5 5.0 1.9 virginica
147 6.5 3.0 5.2 2.0 virginica
148 6.2 3.4 5.4 2.3 virginica
149 5.9 3.0 5.1 1.8 virginica

150 rows × 5 columns

iris.index.name = 'iris_id'
iris
sepal_length sepal_width petal_length petal_width species
iris_id
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
... ... ... ... ... ...
145 6.7 3.0 5.2 2.3 virginica
146 6.3 2.5 5.0 1.9 virginica
147 6.5 3.0 5.2 2.0 virginica
148 6.2 3.4 5.4 2.3 virginica
149 5.9 3.0 5.1 1.8 virginica

150 rows × 5 columns

iris = iris.reset_index()\
    .set_index(['species', 'iris_id'])
iris
level_0 index sepal_length sepal_width petal_length petal_width
species iris_id
setosa 0 0 0 5.1 3.5 1.4 0.2
1 1 1 4.9 3.0 1.4 0.2
2 2 2 4.7 3.2 1.3 0.2
3 3 3 4.6 3.1 1.5 0.2
4 4 4 5.0 3.6 1.4 0.2
... ... ... ... ... ... ... ...
virginica 145 145 145 6.7 3.0 5.2 2.3
146 146 146 6.3 2.5 5.0 1.9
147 147 147 6.5 3.0 5.2 2.0
148 148 148 6.2 3.4 5.4 2.3
149 149 149 5.9 3.0 5.1 1.8

150 rows × 6 columns

iris.groupby('species').mean('mean').plot.barh();

iris.groupby('species').agg('mean').T.setosa.plot.barh();

iris.groupby(['sepal_length','sepal_width']).petal_length\
    .mean()\
    .to_frame('mean petal_length')\
    .plot(style='.', rot=45);