U

Method Chaining

Objects in Python usually have methods that modify the existing object. This means that we can call methods sequentially without having to save out our results in intermediate results.

If we use the same Person class from Appendix S.

class Person(object):
    def __init__(self, fname, lname, age):
        self.fname = fname
        self.lname = lname
        self.age = age

    def celebrate_birthday(self):
        self.age += 1
        return(self)

We can method chain our results if we wanted our person to have two consecutive birthdays.

ka = Person(fname='King', lname='Arthur', age=39)
print(ka.age)
39
# King Arthur has 2 birthdays in a row!
ka.celebrate_birthday().celebrate_birthday()
<__main__.Person at 0x1039903a0>
print(ka.age)
41

We can do something similar in Pandas in Section 4.3 where we tidied up our weather data.

import pandas as pd

weather = pd.read_csv('data/weather.csv')
print(weather.head())
       id year month element  d1   d2   d3  d4    d5  d6   ... 
0 MX17004 2010     1    tmax NaN  NaN  NaN NaN   NaN NaN   ...
1 MX17004 2010     1    tmin NaN  NaN  NaN NaN   NaN NaN   ...
2 MX17004 2010     2    tmax NaN 27.3 24.1 NaN   NaN NaN   ...
3 MX17004 2010     2    tmin NaN 14.4 14.4 NaN   NaN NaN   ...
4 MX17004 2010     3    tmax NaN  NaN  NaN NaN  32.1 NaN   ...
  d22  d23 d24 d25 d26 d27 d28 d29  d30 d31
0 NaN  NaN NaN NaN NaN NaN NaN NaN 27.8 NaN
1 NaN  NaN NaN NaN NaN NaN NaN NaN 14.5 NaN
2 NaN 29.9 NaN NaN NaN NaN NaN NaN  NaN NaN
3 NaN 10.7 NaN NaN NaN NaN NaN NaN  NaN NaN
4 NaN  NaN NaN NaN NaN NaN NaN NaN  NaN NaN
[5 rows x 35 columns]

We first needed to .melt() our date, then .pivot_table(), and finally .reset_index(). Instead of doing each of the steps in separate parts, we can work as if the results returned themself.

weather_tidy = (
    weather
    .melt(
        id_vars=["id", "year", "month", "element"],
        var_name="day",
        value_name="temp",
    )
    .pivot_table(
        index=["id", "year", "month", "day"],
        columns="element",
        values="temp",
    )
    .reset_index()
)

print(weather_tidy)
element      id year month day tmax tmin
0       MX17004 2010     1 d30 27.8 14.5
1       MX17004 2010     2 d11 29.7 13.4
2       MX17004 2010     2  d2 27.3 14.4
3       MX17004 2010     2 d23 29.9 10.7
4       MX17004 2010     2  d3 24.1 14.4
..          ...  ...   ... ...  ...  ...
28      MX17004 2010    11 d27 27.7 14.2
29      MX17004 2010    11 d26 28.1 12.1
30      MX17004 2010    11  d4 27.2 12.0
31      MX17004 2010    12  d1 29.9 13.8
32      MX17004 2010    12  d6 27.8 10.5

[33 rows x 6 columns]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.142.211