<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Constantin von Stegmann on Medium]]></title>
        <description><![CDATA[Stories by Constantin von Stegmann on Medium]]></description>
        <link>https://medium.com/@tinovonstegmann?source=rss-17f497c708a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Ym834iWFw6kQL8HjW_o3Rg.jpeg</url>
            <title>Stories by Constantin von Stegmann on Medium</title>
            <link>https://medium.com/@tinovonstegmann?source=rss-17f497c708a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:31:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tinovonstegmann/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Where’s your (over)head at? Pt II]]></title>
            <link>https://medium.com/vortechsa/wheres-your-over-head-at-pt-ii-f37987532634?source=rss-17f497c708a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f37987532634</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Constantin von Stegmann]]></dc:creator>
            <pubDate>Wed, 16 Sep 2020 19:26:45 GMT</pubDate>
            <atom:updated>2020-09-16T19:26:45.227Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KihRWpLy3FAvYQujr48erg.jpeg" /></figure><p>This is the second article of this series, outlining how to think about data processing code in the Python world, and more specifically, how we can improve our code performance while writing legible, maintainable, production-quality code. You can read Part I <a href="https://medium.com/vortechsa/wheres-your-over-head-at-647ae399cd7c">here</a>.</p><h3>Background</h3><p>So, you’ve decided that Python is the right tool for your use-case. Chances are that if you are working with anything larger than a truly tiny dataset, you will probably default to using the Pandas library; and if you are not, you probably should consider it. Let us briefly review what makes Pandas such a popular tool for data processing.</p><p>The Pandas library has rapidly evolved into the de-facto data processing library in the Python world. One core reason for this is the DataFrame structure, and the mental framework it provides its users. In most cases, real-world data can be very effectively represented in a tabular format; with rows and columns representing observations and features respectively. The Pandas DataFrame structure is arguably the most efficient and intuitive way to represent and interact with this sort of data, in a computational context.</p><p>On top of this, Pandas comes shipped with an incredibly rich ecosystem of tools that make routine operations such as I/O (reading and writing data), transformations, calculations, and even visualisations very, very easy — and in many cases very efficient. Most standard ETL operations boil down to a single method call, or maybe even 2 or 3 methods that can efficiently and legibly be chained together.</p><p>This echoes a core feature mentioned in part 1 of this series, about the strength of the wider Python language, namely how it is built to optimise developer speed. However, as with the Python language as a whole, Pandas’ ease of use and variety of tools means that it is very easy for inexperienced users to write code, which works exactly as intended, but in a terribly inefficient way.</p><p>We are now going to look at some common data processing patterns, and how to do them as efficiently as possible, using Pandas, whilst aiming to maintain a high degree of legibility in our code.</p><h3>Iteration</h3><p>Iterating over some collection of data and executing an arbitrary operation on each element, is the bread and butter of programming. This is no different in Pandas. However, this common use-case is one where less experienced Pandas users often incur some of their biggest performance penalties.</p><p>To understand how we can do this fundamental operation in the most efficient way, we will fall back on this brilliant <a href="https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6">article</a> and accompanying <a href="https://www.youtube.com/watch?v=HN5d490_KKk">talk</a>, by Sofia Heisler. All credit for the tips in the following section goes to Ms. Heisler, so if you find it helpful, please see her original article and talk, and Like, Clap and Share her work.</p><p>Ms. Heisler uses the following function as her baseline example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*9bT9zbyax_RUdrB4" /></figure><p>This example is very applicable to us here at Vortexa, as trigonometric functions like the Haversine distance, form the core of several of our important algorithms. The Haversine function is a simple way of calculating the distance between 2 given points on a sphere. At this stage, all you need to take away from the formula above is that there is no magic, just some simple trigonometric transformations, and arithmetic.</p><p>In her example, Ms. Heisler has a DataFrame containing approximately 1,600 rows with latitude and longitude coordinates. She then wants to calculate the distance from a given coordinate pair, to the coordinates contained in each row of her DataFrame.</p><h3>The for-loop</h3><p>If you are new to Pandas, the default approach you will take here is arguably to use a for-loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*KX64B7AnypG4Aq_O" /></figure><p>Here we see a very common pattern — we define an empty list (distance_list), create an iteration counter (i) which increments between 0 and the length of our data-set, and use this to access data in each row and pass it to our haversine function. We append the result of each loop to our `distance_list` and return the list when the loop is exhausted. How does this approach perform?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*hhbiEL3635EQCcIh" /></figure><p>Our simple looping approach takes just over 600ms. That does not sound too bad, however, if we consider that our haversine function just does simple mathematics — which computers are meant to be optimised for — and the fact that we only have 1,600 records, you may start to see that this approach will quickly become sluggish as we encounter larger datasets.</p><h3>Iterrows</h3><p>Another very common approach used by less experienced Pandas users is the `.iterrows()` method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*O-YeWkITfyqif4Ep" /></figure><p>Iterrows essentially behaves like Python’s `enumerate` function. For every row in our DataFrame, it returns the index value and the row’s data (as a Pandas Series object). This means less clutter in our code, as we no longer need to create an iteration counter or access our data using the clunky `df.iloc` notation. So it arguably results in neater code, but what about performance?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*CdpToHn0gRkypNZL" /></figure><p>That is 4x faster than a basic for-loop! This is a good start, but if you read any number of StackOverflow questions you will quickly see grave words of caution uttered against the use of iterrows. So let’s look at a better alternative.</p><h3>Apply</h3><p>This is the approach most commonly found among intermediate Pandas users, and for good reason. The `.apply()` method is really the swiss army knife of Pandas’ calculation tools. It is more efficient than for-loops or iterrows, and there is almost no function that you cannot package into an apply-friendly shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*66vq7UAePbNr6bIi" /></figure><p>The other advantage we immediately see is how much more succinct an apply call is when compared to loops or iterrows. Our multi-line code snippets from before have been replaced with a simple one-liner. On top of this, we can immediately assign the output of our apply operation to a new column, without first having to store the results elsewhere. Despite the slightly odd ‘lambda’ syntax, we can see that our apply is more legible and succinct than previous attempts and below we can see that it is almost 2x faster than iterrows too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*GaSIagwl6sDluqor" /></figure><p>There is, however, a common misconception that the relative speed of an apply statement is due to it being a vectorized operation. Fortunately, Ms. Heisler provides clear evidence that this is not the case, by using a line-profiler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*n34LYmQ2yiXbqfAI" /></figure><p>Here, we see that every line in our haversine function got called 1631 times, meaning it got called once for every row in the DataFrame. In other words, apply is just a more efficient way of looping. This begs the question, how do we achieve this fabled vectorisation?</p><h3>Vectorization</h3><p>It turns out, in this example, using a vectorised implementation could not be simpler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*SkGd-_qkR8GRHIbb" /></figure><p>Our haversine function has already been written using tools from the powerful NumPy library, so in order to implement this function in a vectorized manner, we simply need to pass the columns (or Series objects) directly into the function as arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*mZq18brF4Efd0Bnn" /></figure><p>This approach turns out to be almost 60x faster than using apply (and at this point almost 400x faster than our first Python for-loop approach)! Using the line-profiler tool again, we can see the reason why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*8YkvaMuU8IMntsyZ" /></figure><p>Now, each line in our function gets called once in its execution. But it turns out that we can do more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*IvccufoJ4B2SGVeA" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*nEuVybDBqWRfjpG-" /></figure><p>This time, while passing our Series objects as arguments to our haversine function, we simply prepend them with a `.values` call — this gives us a further 4x speed improvement. What is going here?</p><p>Calling `.values` on a Pandas Series object returns a NumPy array. There is a lot to unpack and understand when discussing the differences between a NumPy array and Pandas Series, more than we have time for in this article. Two of the core differences to note are that NumPy arrays do not contain a defined index (only an implied integer index), and the mechanisms by which Series and array objects access values in memory also differ. For now, I would suggest using the `.values` approach in cases where your columns contain homogeneous datatypes, and where your calculations consider each row’s values independently.</p><h3>Maths only?</h3><p>So far we have seen some fantastic performance tips for doing mathematical calculations, by iterating over a dataframe in different ways. However, as a comprehensive data processing tool, there are many other use cases we may want to consider when speaking about Pandas performance tips.</p><p>For the following examples, we will be using some of Vortexa’s real-world data. In this case, we have loaded a dataframe of 940,000 rows x 15 columns, containing cargo movements data.</p><h3>Simple Conditionals</h3><p>Applying conditional logic to our data is a common use-case. Let us take an example where we wish to classify cargo movements depending on their respective country of origin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/0*MNePTfqjOV3apH8N" /></figure><p>This is a case where many intermediate users will resort back to an apply statement. After all, it is very simple to conceptualise this sort of operation in a pure function, and then ‘throw’ it at your DataFrame using apply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*hq3tLFl_56DZb2gR" /></figure><p>Here we see that a simple apply took 16s. Granted, we cannot compare this to our previous haversine examples, as we are using a much larger dataset, but this is still incredibly slow. However, you may have noticed that our `find_nordics` function only requires one input, yet we are calling the apply method on the entire DataFrame. It turns out that in these cases we can simply call our apply on the Series we wish to use as our input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*3TL81S03rVQwSL9c" /></figure><p>Although it does not feel like it should make much difference, the performance improvement here is vast (~100x). So, please use this as a word of caution, <em>not all apply(s) are created equal</em>!</p><p>As we have seen before, apply is fundamentally still a looping approach. If we wish to improve the performance of this operation, we can take a page out of the book of high-performance databases. Many relational databases, when asked to execute a conditional statement, do not branch their data down 1 of 2 execution paths, instead they execute both conditionals on each row, and logically combine the results.</p><p>In Pandas, we can do the same by making use of the concept of masks. A mask is created by calling a conditional statement on a column (or columns) of a DataFrame. It will return a Series containing True or False for each row, depending on whether or not it met the conditional logic. We can then use this mask to update our values accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/0*Pj7DAZ6_hOlkuEJ_" /></figure><p>We have again defined a list of countries corresponding to our definition of Nordics. We then created a mask to determine whether each row in the `loading_country` column is in our Nordics subset or not. We then create a new column, setting every row to the default (i.e. `else`) value, and finally use our mask to update only the rows corresponding to Nordic exports. The output is the same as before but achieved almost 5x faster than with a Series apply.</p><p>We can achieve similar performance benefits, by using the NumPy `where` statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*P_0nuRUGKtSqfDOd" /></figure><p>The `where` statement reads almost like a ternary operator in other languages (condition, if true, if false). The performance is virtually identical to our mask approach, so it really boils down to personal preference on legibility as to which approach you choose to take.</p><h3>Multiple Conditionals</h3><p>Things often seem to get a little daunting when we move into the territory of more complex, multiple conditionals. Below you will see an example of a pretty odd piece of logic, but it is there for illustrative purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*PgqHrBBr1XcDl9SV" /></figure><p>Our multiple conditionals function evaluates several values within each row, so we cannot use the more efficient Series apply approach here. As a result, we are left staring blankly at our screens for over a minute, waiting for this apply to complete.</p><p>I have seen plenty of users, familiar with mask syntax, falling back on apply statements when it comes to executing multiple conditionals. Part of the reason is that unlike in simple conditionals, in multiple conditionals, order matters. But fear not, it really is not that difficult to gain serious performance improvements here.</p><p>Let’s take a look at a mask approach first. To do so, we start by creating multiple masks and assigning each Series to a variable name. These masks are mutually exclusive and correspond 1-to-1 with our if/elif statements above. The key to maintaining the correct logical order of execution is simply to flip our traditional if/elif/else loop on its head. We start by defining the default value (the else statement), then we work our way up through the `elif` statements (in the exact reverse order), and finally, apply the mask corresponding to our `if` statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/0*o24tlhmIfF4pKRW1" /></figure><p>This may seem a tad confusing at first, but looking at the performance results, it is certainly worth understanding and locking this type of pattern down in your toolkit. Again, legibility is a major consideration when writing production-quality code, and using this sort of inverted logic can require a little more thinking on the part of someone reviewing or editing the code at a later date. Fortunately, NumPy provides help in this scenario.</p><p>Much like with our simple conditionals, we could use a `.where` statement here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/0*Au8ks2-LsE92LcEp" /></figure><p>The performance is similar, however, the nested statement approach is a mess, and will incur more mental overhead for anyone looking at this code, so in my opinion, this should not be used. The NumPy developers, fortunately, provide an even more useful tool in this case. Enter the `.select` statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/0*DKln7UDliN5QG--f" /></figure><p>The `select` approach is similar to our Pandas masks approach, in that we start by defining a series of conditional statements inside a list. The key difference here is that the statements are listed in the same order as they would be in a traditional if/elif/else statement. We then define a list of results, corresponding to our conditional statements; it is important that these lists align exactly in terms of size and order. Then we simply pass our conditions and results into the `np.select` statement, listing our default (else) value as the final argument.</p><p>Again, our Pandas and NumPy approaches perform similarly, so the key differentiator here is just which of the syntaxes you (and your team) find more legible.</p><h3>Outside the box vs out-of-the-box</h3><p>One final use-case that is admittedly not that common, but as a result also rarely spoken about, is cases where out-of-the-box methods are not fast enough or do not exist. In the following section, we are going to look at an illustrative example of a shift operation in Pandas vs NumPy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/0*jl1lgYU2I1nqar94" /></figure><p>In this case, we wish to find occurrences where the `ves_id` field changes from one row to the next. The top 2 lines show a NumPy implementation of this, the 3rd line shows how this would be done using a Pandas `shift` operation. There is a similar NumPy method available, however, it behaves slightly differently than a Pandas shift, and is not appropriate for this use-case. We can see that the NumPy implementation is more verbose and less legible than a simple `shift` call. However, let us assume that we have a code-base littered with NumPy slicing calls because for whatever reason, our Pandas `shift` was not performant enough (this will almost never be the case, but just humour me for this example). What can we do to keep the performance of the NumPy slicing syntax, but make it more legible?</p><p>We must consider a dogma that virtually every programmer has come across:</p><p><em>“Code is going to be read more times than it is going to be written”</em></p><p>The answer is programming 101 — wrap it in a function. This may sound painfully obvious, but when you are deep into a data processing workflow, it can be easy to write your custom syntax once, and then one more time, and one more… and before you know it, it has spread like knotweed throughout your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/0*uWbnImArP2pqUmqE" /></figure><p>Here, we have simply replaced our list slicing syntax with a function named `array_shift`. The very first benefit which stands out is that the function name is descriptive, and at the very least gives an idea as to what is going on. Looking at the function definition, we see another core benefit — docstrings!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*hjHYGDN4kjrclovg" /></figure><p>Although it is a custom function, we can give users and reviewers plenty of insight as to what is going on, and how it works, including some simple examples. The final benefit is that functions allow us to write comprehensive unit tests. Our array_shift function is testable, so we can ensure that it works as intended every time. Furthermore, using a shared function throughout your codebase, in place of repeated raw syntax, means that any bugs or issues you may discover in your custom approach can be fixed in one place and immediately distributed across every call in your codebase.</p><h3>Conclusion</h3><p>NumPy and Pandas are powerful tools for writing quick and effective data processing workflows. However, it is easy to get it wrong and incur significant performance penalties by using the wrong approaches. So here are some simple tips to bear in mind while creating your workflows.</p><ul><li>Vectorise wherever possible — it will be faster, and in most cases, it will be more legible too.</li><li>If you must loop, use apply, but not all apply(s) are created equal, so ensure that you are apply(ing) correctly.</li><li>“Premature optimisation is the root of all evil” — the famous quote by Donald Knuth rings true here as it does elsewhere in programming. The techniques discussed here are powerful, but fast code is pointless if it generates the wrong output. Start by writing your Pandas code at whichever level you are comfortable with. Make absolutely sure that your logic is sound and that your code behaves as expected. Then, and only then, should you go back and look for common patterns which can be improved upon, ensuring that your optimised code returns exactly what it should.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f37987532634" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vortechsa/wheres-your-over-head-at-pt-ii-f37987532634">Where’s your (over)head at? Pt II</a> was originally published in <a href="https://medium.com/vortechsa">VorTECHsa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where’s your (over)head at?]]></title>
            <link>https://medium.com/vortechsa/wheres-your-over-head-at-647ae399cd7c?source=rss-17f497c708a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/647ae399cd7c</guid>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Constantin von Stegmann]]></dc:creator>
            <pubDate>Wed, 15 Jul 2020 10:23:29 GMT</pubDate>
            <atom:updated>2020-07-15T10:23:29.269Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR </strong>This is the first in a two-part series of articles outlining how to think about data processing code in the Python world, and more specifically, how we can improve our code performance while writing legible, maintainable, production-quality code.</p><p>In this first article, we’re going to evaluate whether Python is the right tool for your use-case, and what you should consider before embarking on a new data processing project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1dDElNW4_KcNbaRjP4eQw.jpeg" /></figure><h3>The Trade-off</h3><p>When benchmarked against other languages, Python consistently ranks toward the lower end of the performance spectrum. In a world where speed is often-times king, it begs the question, why is it such a popular language? The answer to this question is multi-faceted, but one of the core reasons is that Python has been designed, and purpose-built, with the intention of being easy to use.</p><p>Compared to other languages, writing Python code tends to require less thinking on the developer’s behalf, when it comes to how the program manages underlying concepts like data types and memory. What this illustrates, is a very fundamental trade-off when it comes to software engineering, namely, where is our code placing the majority of its overhead, is it on the machine, or the developer?</p><p>Python utilizes (amongst many other design features) abstractions, grammar, and syntax which make the language fast to learn, easy to read and write, and syntactically simple to understand.</p><p>To illustrate this, let’s have a look at a snippet of pure Python code, taken from the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/enhancingperf.html">Pandas documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*AoPZLqXSBOthZfGaAiCKzA.png" /></figure><p>We see 2 functions written in pure Python, which, in terms of our aforementioned trade-off, are a staunch example of the former. The code is clean, concise, and simple. The syntax is arguably as close to pseudo-code as we are going to find in a functioning programming language. Notice how the developer does not have to think much about the likes of variable types, pointers, references, or memory management.</p><p>However, when our pure functions are applied to a large set of data, the performance is going to be sluggish. Part of the reason is that all of these aforementioned concepts, which the developer does not need to explicitly handle, still exist in Python. They are simply hidden from the developer and pushed down on to the machine (or in this case, the Python interpreter). This is <em>one</em> <em>part</em> of the reason why Python code tends to be comparatively slow to run; the machine has to do more thinking on the developer’s behalf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5IRk_rc5SmNE_qCu" /></figure><p>This second snippet (taken from the same documentation), shows the same 2 functions we have previously seen, now implemented in Cython, with the addition of a third function (apply_integrate_f) which optimizes how our previous functions can be applied over a large array of values. This code is highly performant, however, we immediately notice that this code is far more verbose and confusing. The developer is now forced to think about the likes of type annotations, assert statements, and somewhat alien constructs such as the Py_ssize_t object. It is going to be significantly more challenging to read, write, and iterate on when compared to our base Python code, and as such, places more overhead on the developer.</p><h3>Assess the alternatives</h3><p>Writing the same functions which we saw previously, in a language like Kotlin, Rust, C++, or Go would certainly yield better performance than the pure Python code, and in most cases be clearer than the unruly Cython implementation. Even if Python is your daily driver or your first love, you should definitely consider these as viable alternatives when you are about to embark on a new project, particularly when this project calls for snappy, performant execution times.</p><p>But what about existing codebases which are — either by conscious choice, or lack thereof — already written in Python?</p><h3>Is it time to ditch Python?</h3><p>Here at <a href="http://vortexa.com/">Vortexa</a>, we are by no means a ‘Python first’ company. Instead, we tend to adhere to the principle of attempting to use the right tool for the right job. Nevertheless, Python is a prominent feature in our production codebase, largely because a significant proportion of what we do, at its very core, is the processing and modeling of complex real-world data; and when it comes to this domain, very few languages offer as complete of an ecosystem and toolkit as Python does.</p><p>Data processing systems and pipelines are increasingly being faced with the demands of an ever-growing body of available data, as well as the rising desire for real-time analytics. As a result, these systems need to be able to crunch a larger volume of data, as well as being able to do so rapidly, and frequently. Every language has its strengths and weaknesses, and as we have already discussed, despite its ease of use and a rich ecosystem of well-built tools, Python’s Achilles-heel, more often than not, is its runtime performance. In the face of this, we as engineers are forced to ask ourselves whether we should abandon some, or all, of our Python code, which may not perform as well as other languages could, in favour of a new language.</p><figure><img alt="Joel Spolsky, co-founder and former CEO of StackOverflow" src="https://cdn-images-1.medium.com/max/383/0*uamR7A8XFbY-MfXd" /></figure><p>Joel Spolsky (co-founder and former CEO of StackOverflow) published a wildly popular blog post titled <a href="https://www.joelonsoftware.com/2000/04/06/things-you-should-never-do-part-i/">Thing You Should Never Do, Part 1</a>. In this, he made an impassioned argument against the very idea of scrapping existing systems and re-writing them from scratch. Amongst other things, he made the following arguments.</p><p>“When optimizing for performance 1% of the work gets you 99% of the bang” — This is essentially a more extreme manifestation of <a href="https://en.wikipedia.org/wiki/Pareto_principle">Pareto’s Principle</a>, and a common theme in software engineering; the parts of our code, responsible for causing performance bottlenecks, tend to make up a minute fraction of the actual codebase. Moving an entire project into a new language, in order to alleviate the issues arising from such a small fraction of its code, requires understanding, translating, and re-writing the entire codebase. This task alone can incur a significant time commitment for a dev team.</p><p>Understanding the <em>what</em> does not necessarily mean you understand the <em>why</em> — In what can be considered a real-life example of the <a href="https://en.wikipedia.org/wiki/Lindy_effect">Lindy Effect</a>, code which has been around for a long time (particularly in production), tends to accrue significant latent knowledge and functionality. When trying to move this code, it is only natural to attempt to streamline and refactor snippets that look messy, or out of place. But what you will often find is that these odd-looking snippets of code are the results of critical bug fixes, or ‘hacks’ and monkey-patches, written in order to address idiosyncrasies in your data or infrastructure. Discovering these fixes the hard way can turn into a fatal time-sink.</p><p>Subsequently, Joel argues that methodical, incremental refactoring of existing code, is almost always preferable to restarting from scratch.</p><h3>Final thoughts</h3><p>Adding to Joel’s arguments, here a few final thoughts of ours to add into the mix.</p><p>Why did you choose Python in the first place? — More often than not, when a project was first built in Python, it was done so for a reason. In Vortexa’s case, the prevalence of Python in our data processing and modeling code is, in large part, thanks to the power and variety of third-party tools available for the job; none more so than Pandas and NumPy.</p><p>These libraries have become the industry standard for data processing for a reason. They provide APIs and well-thought-out functionality which allow developers to swiftly interact with their data, and to apply a litany of transformations, aggregations, and visualizations while integrating seamlessly with a fantastic number of data-storage formats. Deserting these libraries for other languages means that a relatively standard ETL job, which can be written in tens of lines of Pandas code, can require hundreds of lines of new code (not to mention tests and adjusted deployment code), as well as an expensive mental paradigm shift.</p><p>There is one more question to ask yourself; is your Python code even as performant as it <em>could </em>be? Even in large systems, covering multiple modules and steps, the fundamental principles of algorithmic complexity still apply. Do you know if your algorithms are running in quadratic, logarithmic, linear, or constant time, and can you improve upon them? In a similar vein, can you alter how much data your code needs to process? Does it have to re-process every data point every time, or can you do delta calculations or incremental processing?</p><p>In summary, when you are starting a new project, ask yourself carefully where you want (or can afford) to have your overhead applied. Are runtime performance and developer control the top priorities for the code you are about to write? In which case, Python is probably not the right tool for the job. However, if your code needs to handle messy, frequently changing real-world data, and you can afford to sacrifice a bit of runtime performance in favour of flexible, highly accessible code with fast developer iteration times, then the likes of Python and Pandas should probably be your go-to.</p><p>Regardless of which choice you make, ensure that you allocate adequate thought before starting. Rewriting existing code from scratch, at a later date is a risky and time-consuming endeavor, and it can be hard to justify months of developer time being invested into such a task when the resulting output yields no new features or discernable improvements for the consumer.</p><p>If you already have a significant amount of code written in Pandas, stay tuned for the second part of this post, where we will speak about common performance issues, and how to address them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=647ae399cd7c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vortechsa/wheres-your-over-head-at-647ae399cd7c">Where’s your (over)head at?</a> was originally published in <a href="https://medium.com/vortechsa">VorTECHsa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>