I was hoping to build a library. I’m going to write about how far I got, where the barrier is, and what I plan to do next. This follows from the introduction to Munkres I wrote earlier this month.
The algorithm requires manipulation of the elements in a grid as well as it’s rows and columns. I’m going to start this series by explaining how I tried to make the rows and column manipulable1completely guessed at that, genuinely amazed it’s a real word by extending the
This is probably going to be moderately technical. I’m going to be walking through the code so there’s no need to go and look for it, but if you’d like to you can find it on Github.
import pandas as pd @pd.api.extensions.register_series_accessor("munkres") class PandasMunkresAccessor: def __init__(self, pandas_obj): self._obj = pandas_obj self.covered = False def cover(self): """ Marks all elements in this series as 'covered' and also itself :return: """ self._obj.apply(MunkresElement.cover) self.covered = True def uncover(self): """ Marks all elements in this series as uncovered and also itself :return: """ self._obj.apply(MunkresElement.uncover) self.covered = False
This is the first class I’m using. It uses a decorator, which is a sort of magic thing we have in Python. I’m going to avoid explaining decorators for the moment2because I don’t fully understand them myself yet and just say that this is a way of extending an existing class in Pandas – the
Series class. It adds two methods and an attribute that I can access through
Series.munkres – you can see where the “munkres” part comes from in the second line of code.
The way I’ve modified it is by adding an attribute,
covered. There are also quasi “setter” and “getter” methods – one that covers all the objects in the
Series and itself, and one that does the reverse.
I’ve added this because part of the algorithm involves covering rows and columns in a grid, and I thought this would be the simplest way to implement that in code. I am not yet sure whether I’m right, so I’m writing tests to check my understanding of how a
Series is actually initialised.
(This is by far the best thing about writing code: if you don’t know how a thing works, you can construct a test to check. Most things in life aren’t like that.)
You’ll notice that when the extended
Series.cover method is called, it calls another method –
.apply. This is a method in the base
Series class, and it allows you to apply a function to every element in the series. In this case, I’m applying a method from the
MunkresElement class, which is just as well because all the items in the
MunkresElements. We know this because when we initialised the object in which we find the
Series, we fill it with
November is National Blog Posting Month, or NaBloPoMo. I’ll be endeavouring to write one blog post per day in the month of November 2019 – some short and sweet, others long and boring.