Scripting around a pandas DataFrame can turn into an awkward pile of (not-so-)good old spaghetti code. Me and my colleagues use this package a lot and while we try to stick to good programming practices, like splitting code in modules and unit testing, sometimes we still get in the way of one another by producing confusing code.
I have gathered some tips and pitfalls to avoid in order to make pandas code clean and infallible. Hopefully youll find them useful too. We'll get some help from Robert C. Martin's classic Clean code specifically for the context of the pandas package. TL;DR at the end.
Lets begin by observing some faulty patterns inspired by real life. Later on, well try to rephrase that code in order to favor readability and control.
Pandas DataFrames are value-mutable [2, 3] objects. Whenever you alter a mutable object, it affects the exact same instance that you originally created and its physical location in memory remains unchanged. In contrast, when you modify an immutable object (eg. a string), Python goes to create a whole new object at a new memory location and swaps the reference for the new one.
This is the crucial point: in Python, objects get passed to the function by assignment [4, 5]. See the graph: the value of df has been assigned to variable in_df when it was passed to the function as an argument. Both the original df and the in_df inside the function point to the same memory location (numeric value in parentheses), even if they go by different variable names. During the modification of its attributes, the location of the mutable object remains unchanged. Now all other scopes can see the changes too they reach to the same memory location.
Actually, since we have modified the original instance, its redundant to return the DataFrame and assign it to the variable. This code has the exact same effect:
Heads-up: the function now returns None, so be careful not to overwrite the df with None if you do perform the assignment: df = modify_df(df).
In contrast, if the object is immutable, it will change the memory location throughout the modification just like in the example below. Since the red string cannot be modified (strings are immutable), the green string is created on top of the old one, but as a brand new object, claiming a new location in memory. The returned string is not the same string, whereas the returned DataFrame was the exact same DataFrame.
The point is, mutating DataFrames inside functions has a global effect. If you dont keep that in mind, you may:
Well fix that problem later, but here is another don't before we pass to do's
The design from the previous section is actually an anti-pattern called output argument [1 p.45]. Typically, inputs of a function will be used to create an output value. If the sole point of passing an argument to a function is to modify it, so that the input argument changes its state, then its challenging our intuitions. Such behavior is called side effect [1 p.44] of a function and those should be well documented and minimized because they force the programmer to remember the things that go in the background, therefore making the script error-prone.
When we read a function, we are used to the idea of information going in to the function through arguments and out through the return value. We dont usually expect information to be going out through the arguments. [1 p.41]
Things get even worse if the function has a double responsibility: to modify the input and to return an output. Consider this function:
It does return a value as you would expect, but it also permanently modifies the original DataFrame. The side effect takes you by surprise - nothing in the function signature indicated that our input data was going to be affected. In the next step, we'll see how to avoid this kind of design.
To eliminate the side effect, in the code below we have created a new temporary variable instead of modifying the original DataFrame. The notation lengths: pd.Series indicates the datatype of the variable.
This function design is better in that it encapsulates the intermediate state instead of producing a side effect.
Another heads-up: please be mindful of the differences between deep and shallow copy [6] of elements from the DataFrame. In the example above we have modified each element of the original df["name"] Series, so the old DataFrame and the new variable have no shared elements. However, if you directly assign one of the original columns to a new variable, the underlying elements still have the same references in memory. See the examples:
You can print out the DataFrame after each step to observe the effect. Remember that creating a deep copy will allocate new memory, so its good to reflect whether your script needs to be memory-efficient.
Maybe for whatever reason you want to store the result of that length computation. Its still not a good idea to append it to the DataFrame inside the function because of the side effect breach as well as the accumulation of multiple responsibilities inside a single function.
I like the One Level of Abstraction per Function rule that says:
We need to make sure that the statements within our function are all at the same level of abstraction.
Mixing levels of abstraction within a function is always confusing. Readers may not be able to tell whether a particular expression is an essential concept or a detail. [1 p.36]
Also lets employ the Single responsibility principle [1 p.138] from OOP, even though were not focusing on object-oriented code right now.
Why not prepare your data beforehand? Lets split data preparation and the actual computation in separate functions.:
The individual task of creating the name_len column has been outsourced to another function. It does not modify the original DataFrame and it performs one task at a time. Later we retrieve the max element by passing the new column to another dedicated function. Notice how the aggregating function is generic for Collections.
Lets brush the code up with the following steps:
The way we have split the code really makes it easy to go back to the script later, take the entire function and reuse it in another script. We like that!
There is one more thing we can do to increase the level of reusability: pass column names as parameters to functions. The refactoring is going a little bit over the top, but sometimes it pays for the sake of flexibility or reusability.
Did you ever figure out that your preprocessing was faulty after weeks of experiments on the preprocessed dataset? No? Lucky you. I actually had to repeat a batch of experiments because of broken annotations, which could have been avoided if I had tested just a couple of basic functions.
Important scripts should be tested [1 p.121, 7]. Even if the script is just a helper, I now try to test at least the crucial, most low-level functions. Lets revisit the steps that we made from the start:
1. I am not happy to even think of testing this, its very redundant and we have paved over the side effect. It also tests a bunch of different features: the computation of name length and the aggregation of result for the max element. Plus it fails, did you see that coming?
2. This is much better we have focused on one single task, so the test is simpler. We also dont have to fixate on column names like we did before. However, I think that the format of the data gets in the way of verifying the correctness of the computation.
3. Here we have cleaned up the desk. We test the computation function inside out, leaving the pandas overlay behind. Its easier to come up with edge cases when you focus on one thing at a time. I figured out that Id like to test for None values that may appear in the DataFrame and I eventually had to improve my function for that test to pass. A bug caught!
4. Were only missing the test for find_max_element:
One additional benefit of unit testing that I never forget to mention is that it is a way of documenting your code, as someone who doesnt know it (like you from the future) can easily figure out the inputs and expected outputs, including edge cases, just by looking at the tests. Double gain!
These are some tricks I found useful while coding and reviewing other peoples code. Im far from telling you that one or another way of coding is the only correct one you take what you want from it, you decide whether you need a quick scratch or a highly polished and tested codebase. I hope this thought piece helps you structure your scripts so that youre happier with them and more confident about their infallibility.
If you liked this article, I would love to know about it. Happy coding!
TL;DR
Theres no one and only correct way of coding, but here are some inspirations for scripting with pandas:
Donts:
- dont mutate your DataFrame too much inside functions, because you may lose control over what and where gets appended/removed from it,
- dont write methods that mutate a DataFrame and return nothing because that's confusing.
Dos:
- create new objects instead of modifying the source DataFrame and remember to make a deep copy when needed,
- perform only similar-level operations inside a single function,
- design functions for flexibility and reusability,
- test your functions because this helps you design cleaner code, secure against bugs and edge cases and document it for free.
The graphs were created by me using Miro. The cover image was also created by me using the Titanic dataset and GIMP (smudge effect).
Read more from the original source:
- Global Data Science Platform Market Report 2020 Industry Trends, Share and Size, Complete Data Analysis across the Region and Globe, Opportunities and... [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Data Science and Machine-Learning Platforms Market Size, Drivers, Potential Growth Opportunities, Competitive Landscape, Trends And Forecast To 2027 -... [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Industrial Access Control Market 2020-28 use of data science in agriculture to maximize yields and efficiency with top key players - TechnoWeekly [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- IPG Unveils New-And-Improved Copy For Data: It's Not Your Father's 'Targeting' 11/11/2020 - MediaPost Communications [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Risks and benefits of an AI revolution in medicine - Harvard Gazette [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- UTSA to break ground on $90 million School of Data Science and National Security Collaboration Center - Construction Review [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Addressing the skills shortage in data science and analytics - IT-Online [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Data Science Platform Market Research Growth by Manufacturers, Regions, Type and Application, Forecast Analysis to 2026 - Eurowire [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- 2020 AI and Data Science in Retail Industry Ongoing Market Situation with Manufacturing Opportunities: Amazon Web Services, Baidu Inc., BloomReach... [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Endowed Chair of Data Science job with Baylor University | 299439 - The Chronicle of Higher Education [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Data scientists gather 'chaos into something organized' - University of Miami [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- AI Update: Provisions in the National Defense Authorization Act Signal the Importance of AI to American Competitiveness - Lexology [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Healthcare Innovations: Predictions for 2021 Based on the Viewpoints of Analytics Thought Leaders and Industry Experts | Quantzig - Business Wire [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Poor data flows hampered governments Covid-19 response, says the Science and Technology Committee - ComputerWeekly.com [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Ilia Dub and Jasper Yip join Oliver Wyman's Asia partnership - Consultancy.asia [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Save 98% off the Complete Excel, VBA, and Data Science Certification Training Bundle - Neowin [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Data Science for Social Good Programme helps Ofsted and World Bank - India Education Diary [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Associate Professor of Fisheries Oceanography named a Cooperative Institute for the North Atlantic Region (CINAR) Fellow - UMass Dartmouth [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Rapid Insight To Host Free Webinar, Building on Data: From Raw Piles to Data Science - PR Web [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- This Is the Best Place to Buy Groceries, New Data Finds | Eat This Not That - Eat This, Not That [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Which Technology Jobs Will Require AI and Machine Learning Skills? - Dice Insights [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Companies hiring data scientists in NYC and how much they pay - Business Insider [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Calling all rock stars: hire the right data scientist talent for your business - IDG Connect [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- How Professors Can Use AI to Improve Their Teaching In Real Time - EdSurge [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- BCG GAMMA, in Collaboration with Scikit-Learn, Launches FACET, Its New Open-Source Library for Human-Explainable Artificial Intelligence - PRNewswire [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Data Science Platform Market Insights, Industry Outlook, Growing Trends and Demands 2020 to 2025 The Courier - The Courier [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- UBIX and ORS GROUP announce partnership to democratize advanced analytics and AI for small and midmarket organizations - PR Web [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Praxis Business School is launching its Post Graduate Program in Data Engineering in association with Knowledge Partners - Genpact and LatentView... [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- What's So Trendy about Knowledge Management Solutions Market That Everyone Went Crazy over It? | Bloomfire, CSC (American Productivity & Quality... [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Want to work in data? Here are 6 skills you'll need Just now - Siliconrepublic.com [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Data, AI and babies - BusinessLine [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Here's how much Amazon pays its Boston-based employees - Business Insider [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Datavant and Kythera Increase the Value Of Healthcare Data Through Expanded Data Science Platform Partnership - GlobeNewswire [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- O'Reilly Analysis Unveils Python's Growing Demand as Searches for Data Science, Cloud, and ITOps Topics Accelerate - Business Wire [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Book Review: Hands-On Exploratory Data Analysis with Python - insideBIGDATA [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- The 12 Best R Courses and Online Training to Consider for 2021 - Solutions Review [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Software AG's TrendMiner 2021.R1 Release Puts Data Science in the Hands of Operational Experts - Yahoo Finance [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- The chief data scientist: Who they are and what they do - Siliconrepublic.com [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Berkeley's data science leader dedicated to advancing diversity in computing - UC Berkeley [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Awful Earnings Aside, the Dip in Alteryx Stock Is Worth Buying - InvestorPlace [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Why Artificial Intelligence May Not Offer The Business Value You Think - CMSWire [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Getting Prices Right in 2021 - Progressive Grocer [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Labelbox raises $40 million for its data labeling and annotation tools - VentureBeat [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- How researchers are using data science to map wage theft - SmartCompany.com.au [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Ready to start coding? What you need to know about Python - TechRepublic [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Women changing the face of science in the Middle East and North Africa - The Jerusalem Post [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Mapping wage theft with data science - The Mandarin [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Data Science Platform Market 2021 Analysis Report with Highest CAGR and Major Players like || Dataiku, Bridgei2i Analytics, Feature Labs and More KSU... [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Data Science Impacting the Pharmaceutical Industry, 2020 Report: Focus on Clinical Trials - Data Science-driven Patient Selection & FDA... [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- App Annie Sets New Bar for Mobile Analytics with Data Science Innovations - PRNewswire [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Data Science and Analytics Market 2021 to Showing Impressive Growth by 2028 | Industry Trends, Share, Size, Top Key Players Analysis and Forecast... [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- How Can We Fix the Data Science Talent Shortage? Machine Learning Times - The Predictive Analytics Times [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Opinion: How to secure the best tech talent | Human Capital - Business Chief [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Following the COVID science: what the data say about the vaccine, social gatherings and travel - Chicago Sun-Times [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Automated Data Science and Machine Learning Platforms Market Technological Growth and Precise Outlook 2021- Microsoft, MathWorks, SAS, Databricks,... [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- 9 investors discuss hurdles, opportunities and the impact of cloud vendors in enterprise data lakes - TechCrunch [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Rapid Insight to Present at Data Science Salon's Healthcare, Finance, and Technology Virtual Event - PR Web [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Aunalytics Acquires Naveego to Expand Capabilities of its End-to-End Cloud-Native Data Platform to Enable True Digital Transformation for Customers -... [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Tech Careers: In-demand Courses to watch out for a Lucrative Future - Big Easy Magazine [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Willis Towers Watson enhances its human capital data science capabilities globally with the addition of the Jobable team - GlobeNewswire [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Global Data Science Platform Market 2021 Industry Insights, Drivers, Top Trends, Global Analysis And Forecast to 2027 KSU | The Sentinel Newspaper -... [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- A Comprehensive Guide to Scikit-Learn - Built In [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Industry VoicesBuilding ethical algorithms to confront biases: Lessons from Aotearoa New Zealand - FierceHealthcare [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- How Intel Employees Volunteered Their Data Science Expertise To Help Costa Rica Save Lives During the Pandemic - CSRwire.com [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Learn About Innovations in Data Science and Analytic Automation on an Upcoming Episode of the Advancements Series - Yahoo Finance [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Symposium aimed at leveraging the power of data science for promoting diversity - Penn State News [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Rochester to advance research in biological imaging through new grant - University of Rochester [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- SoftBank Joins Initiative to Train Diverse Talent in Data Science and AI - Entrepreneur [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Participating in SoftBank/ Correlation One Initiative - Miami - City of Miami [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Increasing Access to Care with the Help of Big Data | Research Blog - Duke Today [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Heres how Data Science & Business Analytics expertise can put you on the career expressway - Times of India [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Yelp data shows almost half a million new businesses opened during the pandemic - CNBC [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Postdoctoral Position in Transient and Multi-messenger Astronomy Data Science in Greenbelt, MD for University of MD Baltimore County/CRESST II -... [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- DefinedCrowd CEO Daniela Braga on the future of AI, training data, and women in tech - GeekWire [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Gartner: AI and data science to drive investment decisions rather than "gut feel" by mid-decade - TechRepublic [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Jupyter has revolutionized data science, and it started with a chance meeting between two students - TechRepublic [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Working at the intersection of data science and public policy | Penn Today - Penn Today [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- The Future of AI: Careers in Machine Learning - Southern New Hampshire University [Last Updated On: April 4th, 2021] [Originally Added On: April 4th, 2021]
- SMU meets the opportunities of the data-driven world with cutting-edge research and data science programs - The Dallas Morning News [Last Updated On: April 4th, 2021] [Originally Added On: April 4th, 2021]
- Data, Science, and Journalism in the Age of COVID - Pulitzer Center on Crisis Reporting [Last Updated On: April 4th, 2021] [Originally Added On: April 4th, 2021]