Operators and Dunder Methods
Learn the operators and magic of dunder methods found in Series.
We'll cover the following...
Operators or dunder methods (short for double underscore methods) are the protocols that determine how the Python language reacts to operations. For example, when we use the +
operation, Python is dispatching to the __add__
method. When we use a loop with a for
statement, Python dispatches to the __iter__
method.
This won’t be a deep treatise on dunder methods or magic methods.
Let’s look at how this works with a pandas Series.
Dunder methods
Here’s an example in pure Python:
print(2 + 4)
When we run the code above, under the covers, Python runs this:
print((2).__add__(4))
A Python integer object that has a __add__
method responds to the +
operation. Because a Series object has this method, we can call +
on it. There’s also a __div__
method that supports division. One way to calculate the average of the two Series is the following:
print((city_mpg + highway_mpg)/2)
Note that the type of the result is float64
.
Index alignment
Note that we can apply most math operations on a Series with another Series, and we can also use a ...