S

Classes

Python is an object-oriented language, meaning that everything you create or use is a “class”. Classes allow the programmer to group relevant functions and methods together. In Pandas, Series and DataFrame are classes, and each has its own attributes (e.g., .shape) and methods (e.g., .apply()). While it’s not this book’s intention to give a lesson on object-oriented programming, I want to very quickly cover classes, with the hope that this information will help you navigate the official documentation and understand why things are the way they are.

What’s nice about classes is that the programmer can define any class for their intended purpose. The following class represents a person. There are a first name (fname), a last name (lname), and an age (age) associated with each person. When the person celebrates their birthday (celebrate_birthday), the age increases by 1.

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)

With the Person class created, we can use it in our code. Let’s create an instance of our Person.

ka = Person(fname='King', lname='Arthur', age=39)

This created a Person—King Arthur, age 39—and saved him to a variable named ka. We can then get some attributes from ka (note that attributes are not functions or methods, so they do not have round brackets).

print(ka.fname)
King
print(ka.lname)
Arthur
print(ka.age)
39

Finally, we can call the method on our class to increment the age.

ka.celebrate_birthday()
print(ka.age)
40

The Pandas Series and DataFrame objects are more complex versions of our Person class. The general concepts are the same, though. We can instantiate any new class to a variable, and access its attributes or call its methods.

..................Content has been hidden....................

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