Chaining Notation

What is Chaining?


404 image

Attribution

cereal = pd.read_csv('data/cereal.csv')
manufacturer_column = cereal['mfr']
manufacturer_column.value_counts()
mfr
K    23
G    22
P     9
     ..
Q     8
N     6
A     1
Name: count, Length: 7, dtype: int64


cereal['mfr'].value_counts()
mfr
K    23
G    22
P     9
     ..
Q     8
N     6
A     1
Name: count, Length: 7, dtype: int64
mfr_k = cereal[cereal['mfr'] == 'K']
csr_df = mfr_k.loc[:, ["calories", "sugars", "rating"]]
cereal_mean = csr_df.mean()
cereal_mean
calories    108.695652
sugars        7.565217
rating       44.038462
dtype: float64


cereal_mean = cereal[cereal['mfr'] == 'K'].loc[:, ["calories", "sugars", "rating"]].mean()
cereal_mean
calories    108.695652
sugars        7.565217
rating       44.038462
dtype: float64
cereal_mean = cereal[cereal['mfr'] == 'K'].loc[:, ["calories", "sugars", "rating"]].mean()

cereal_mean
calories    108.695652
sugars        7.565217
rating       44.038462
dtype: float64


cereal_mean = (cereal[cereal['mfr'] == 'K'].loc[:, ["calories", "sugars", "rating"]]
                                           .mean()
              )
              
cereal_mean.head()
calories    108.695652
sugars        7.565217
rating       44.038462
dtype: float64

Coding Preferences

  • Chaining has advantages and disadvantages.
  • Increases the readability of our code.
  • Comments are extremely important with of without chaining.

Let’s apply what we learned!