{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Ibrahim Salami",
  "title_listed": "I Reduced My Pandas Runtime by 95% — Here's What I Was Doing Wrong",
  "keywords": "",
  "domain": "数据处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/i-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong/",
  "publish_date": "2026-04-26",
  "corpus_stage": "",
  "notes": "",
  "id": "02dc776eeb7c",
  "collected_at": "2026-10-02T11:44:09",
  "title": "I Reduced My Pandas Runtime by 95% — Here’s What I Was Doing Wrong | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Programming](https://towardsdatascience.com/category/programming/)\n# I Reduced My Pandas Runtime by 95% — Here’s What I Was Doing Wrong\nMost slow Pandas code \"works\", until it doesn't. Learn how to spot hidden bottlenecks, avoid costly row-wise operations, and know when Pandas is no longer enough.\n[Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\nApril 26, 202617 min read\n![](../images/000.jpg)\nCreated with Nano Banana\nI've been learning Pandas for some time now. Nothing too crazy though. Just basic data cleaning, exploratory data analysis, and some essential functions. I've also explored things like method chaining for cleaner, more organized code, and operations that silently break your Pandas workflow, both of which I've written about before.\nI never really thought about runtime. Honestly, if my code ran without errors and gave me the output I needed, I was happy. Even if it took a few minutes for all my notebook cells to finish, I didn't care. No errors meant no problems, right?\nThen I came across the concept of vectorization. And something clicked.\nI went down the rabbit hole, as I usually do. The more I read, the more I realized that \"no errors\" and \"efficient code\" are two very different things. Your Pandas code can be completely correct and still be quietly terrible at scale.\nSo this article is me documenting what I found. The mistakes that slow Pandas code down, why they happen, how to fix them, and when Pandas itself might be the bottleneck. If you've ever run a notebook and just assumed the wait time was normal, this one's for you.\nLearn this step by step with the interactive [Computer Science](https://roadmap.sh/computer-science) roadmap.\n## Why \"Working Code\" Isn't Good Enough\nThere's a reason this took me a while to think about. Pandas is designed to be forgiving. You can write code in a dozen different ways and most of them will work. You get your output, your dataframe looks right, and you move on.\nBut that flexibility comes with a hidden cost.\nUnlike SQL or production-grade data systems, Pandas doesn't force you to think about efficiency. It doesn't warn you when you're doing something expensive. It just... does it. Slowly, sometimes. But it does it.\nThink about it this way. SQL has a query optimizer. It looks at what you're asking for and figures out the most efficient way to get it. Pandas doesn't have that. It trusts you to write efficient code. And if you don't know what efficient looks like, you'll never know you're missing it.\nThe result is that a lot of Pandas code in the wild is what I'd call politely inefficient. It works on small datasets. It works on medium datasets with a little patience. But the moment you throw real-world data at it, something that's a few hundred thousand rows or more, the cracks start to show. What used to take seconds now takes minutes. What took minutes becomes unusable.\nAnd the frustrating part is nothing looks wrong. No errors. No warnings. Just a slow notebook and a spinning cursor.\nThat's the trap. Pandas optimizes for convenience, not speed. And convenience is great, until it isn't.\nSo the first shift is a mindset one: working code and efficient code are not the same thing. Once that clicks, everything else follows.\n## Profiling: Stop Guessing, Start Measuring\nHere's something I noticed while going down this rabbit hole. Most people, when they feel like their code is slow, do one of two things. They either rewrite the whole thing from scratch hoping something improves, or they just accept it and wait.\nNeither of those is the right move.\nThe right move is to measure first. You can't optimize what you haven't identified. And more often than not, the part of your code you _think_ is slow isn't actually the problem.\nPandas gives you a few simple tools to start with.\n###  `%timeit` -- Know How Long Things Actually Take\n`%timeit` is a Jupyter magic command that runs a line of code multiple times and gives you the average execution time. It's the simplest way to compare two approaches and know, concretely, which one is faster.\npython\n\n```\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({\n    'sales': np.random.randint(100, 10000, size=100_000),\n    'discount': np.random.uniform(0.0, 0.5, size=100_000)\n})\n\n# Approach A\n%timeit df.apply(lambda row: row['sales'] * row['discount'], axis=1)\n\n# Approach B\n%timeit df['sales'] * df['discount']\n```\n\nOn a dataset of 100,000 rows, the difference is not subtle:\nmarkup\n\n```\n1.91 s ± 228 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)316 μs ± 14 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n```\n\nSame output. Completely different cost. That's the kind of thing you'd never notice by just running the cell once and moving on.\n###  `df.info()` and `df.memory_usage()` -- Know What You're Carrying\nSpeed isn't just about computation. Memory plays a huge role too. A dataframe that's bloated with the wrong data types will slow everything down before you've even written a single transformation.\npython\n\n```\ndf.info()\n```\n\n**Output:**\nmarkup\n\n```\n<class 'pandas.core.frame.DataFrame'>RangeIndex: 100000 entries, 0 to 99999Data columns (total 2 columns): #   Column    Non-Null Count   Dtype  ---  ------    --------------   -----   0   sales     100000 non-null  int64   1   discount  100000 non-null  float64dtypes: float64(1), int64(1)memory usage: 1.5 MB\n```\n\nTo check the memory usage\npython\n\n```\ndf.memory_usage(deep=True)\n```\n\n**Output:**\nmarkup\n\n```\nIndex          132sales       400000discount    800000dtype: int64\n```\n\nHere, we can see that `discount` is taking up twice the space. This is because `discount` is stored as a \"heavier\" number type (`float64`) while `sales` is stored in a \"lighter\" type (`int32`).\nThis becomes especially important when you're working with string columns or object types that are secretly eating memory. We'll come back to this in the next section.\n### The Profiling Mindset\nThe tools themselves are simple. The shift is in how you approach your code. Before you optimize anything, ask: _where is the time actually going?_ Measure the slow parts. Compare alternatives. Let the numbers tell you what to fix.\nBecause what feels slow and what is slow are often two different things entirely.\n## Mistake #1: Row-wise Operations (The Silent Killer)\nIf there's one thing I kept seeing come up again and again while researching this topic, it was this: people looping through Pandas dataframes row by row. And I get it. It feels natural. You think about your data one row at a time, so you write code that processes it one row at a time.\nThe problem is, that's not how Pandas thinks.\n### How Pandas Actually Works\nPandas is built on top of NumPy, which stores data in contiguous blocks of memory, column by column. This means Pandas is heavily optimized to operate on entire columns at once. When you do that, it runs fast, low-level, vectorized operations under the hood.\nWhen you loop through rows instead, you're essentially bypassing all of that. You're dropping down into pure Python, one row at a time, with all the overhead that comes with it. On a small dataset you'll never notice. On a large one, you'll be waiting a long time.\nThere are two patterns that show up constantly.\n### `.iterrows()`\npython\n\n```\n# Calculating a discounted price row by row\ndiscounted_prices = []\n\nfor index, row in df.iterrows():\n    discounted_prices.append(row['sales'] * (1 - row['discount']))\n\ndf['discounted_price'] = discounted_prices\n```\n\n  \nThis works. It will give you the right answer. But on a dataframe with 100,000 rows, it is painfully slow.\npython\n\n```\n%timeit [row['sales'] * (1 - row['discount']) for index, row in df.iterrows()]\n```\n\n**Output:**\nmarkup\n\n```\n10.2 s ± 1.73 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n```\n\n### `.apply(axis=1)`\nThis one is sneakier because it looks more \"Pandas-like.\" But applying a function across axis=1 means applying it row by row, which is essentially the same problem.\npython\n\n```\n%timeit df.apply(lambda row: row['sales'] * (1 - row['discount']), axis=1)\n```\n\n**Output:**\nmarkup\n\n```\n1.5 s ± 88.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n```\n\nFaster than `.iterrows()`, but still operating row by row. Still slow.\n### The Fix: Vectorized Operations\nHere's the same calculation, done the way Pandas actually wants you to do it:\npython\n\n```\ndf['discounted_price'] = df['sales'] * (1 - df['discount'])\n```\n\nLet's time it\npython\n\n```\n%timeit df['sales'] * (1 - df['discount'])\n```\n\nOutput:\nmarkup\n\n```\n688 μs ± 236 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n```\n\nThat's it. One line. No loop. No lambda. And it's roughly **14,800x faster than**`.iterrows()` and **2,180x faster than**`**.apply(axis=1)**`**.**\nWhat's happening here is that Pandas passes the entire column to NumPy, which executes the operation at the C level across the whole array at once. No Python overhead. No row-by-row iteration. Just fast, low-level computation.\n### When `.apply()` Is Actually Fine\nTo be fair, `.apply()` isn't always the villain. When you're applying a function column-wise (axis=0, which is the default), it's often perfectly reasonable. The issue is specifically `axis=1`, which forces row-by-row execution.\nAnd sometimes your logic is genuinely complex enough that a clean vectorized expression isn't obvious. In those cases, `np.vectorize()` or `np.where()` can give you something closer to vectorized performance while still letting you express conditional logic clearly.\npython\n\n```\n# Instead of this\ndf['category'] = df.apply(\n    lambda row: 'high' if row['sales'] > 5000 else 'low', axis=1\n)\n\n# Do this\ndf['category'] = np.where(df['sales'] > 5000, 'high', 'low')\n```\n\npython\n\n```\n%timeit df.apply(lambda row: 'high' if row['sales'] > 5000 else 'low', axis=1)\n%timeit np.where(df['sales'] > 5000, 'high', 'low')\n```\n\nOutput:\nmarkup\n\n```\n1.31 s ± 189 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)1.3 ms ± 180 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n```\n\nSame result. About **1,000x faster**.\n### The Rule of Thumb\nIf you're writing a loop over rows in Pandas, stop and ask yourself: can this be expressed as a column operation? Nine times out of ten, the answer is yes. And when it is, the performance difference is transformative.\nIf you're looping through rows, you're not using Pandas. You're using Python with extra steps.\n## Mistake #2: Unnecessary Copies and Memory Bloat\nRow-wise operations get a lot of attention when people talk about Pandas performance. Memory gets a lot less. Which is a shame, because in my experience reading about this, bloated memory is just as responsible for slow notebooks as bad computation.\nHere's the thing. Pandas operations don't always modify your dataframe in place. A lot of them quietly create a brand new copy of your data behind the scenes. Do that enough times, and you're not just holding one dataframe in memory. You're holding several, all at once, without realizing it.\n### The Hidden Cost of Chained Operations\nChained operations are a common culprit. They look clean and readable, but each step can generate an intermediate copy that sits in memory until garbage collection cleans it up.\npython\n\n```\n# Each step here potentially creates a new copy\ndf2 = df[df['sales'] > 1000]\ndf3 = df2.dropna()\ndf4 = df3.reset_index(drop=True)\ndf5 = df4[['sales', 'discount']]\n```\n\nBy the time you get to `df5`, you potentially have five versions of your data floating around in memory simultaneously. On a small dataset this is invisible. On a large one, this is how you run out of RAM.\n### Temporary Columns That Stick Around\nAnother pattern that quietly eats memory is creating columns you only needed temporarily.\npython\n\n```\ndf['gross_revenue'] = df['sales'] * df['quantity']\ndf['tax'] = df['gross_revenue'] * 0.075\ndf['net_revenue'] = df['gross_revenue'] - df['tax']\n\n# But you only actually needed net_revenue\n```\n\n`gross_revenue` and `tax` are now permanent columns in your dataframe, taking up memory for the rest of your notebook even though they were just stepping stones.\nThe fix is simple. Either compute directly:\npython\n\n```\ndf['net_revenue'] = (df['sales'] * df['quantity']) * (1 - 0.075)\n```\n\nOr drop them as soon as you're done:\npython\n\n```\ndf.drop(columns=['gross_revenue', 'tax'], inplace=True)\n```\n\n### Wrong Data Types Are Quietly Expensive\nThis one surprised me when I came across it. By default, Pandas is quite generous with how much memory it assigns to each column. Integer columns get `int64`. Float columns get `float64`. String columns become `object` type, which is one of the most memory-hungry types in Pandas.\nLet's see what that actually looks like:\npython\n\n```\ndf = pd.DataFrame({\n    'order_id': np.random.randint(1000, 9999, size=100_000),\n    'sales': np.random.randint(100, 10000, size=100_000),\n    'discount': np.random.uniform(0.0, 0.5, size=100_000),\n    'region': np.random.choice(['north', 'south', 'east', 'west'], size=100_000)\n})\n\ndf.memory_usage(deep=True)\n```\n\nOutput\nmarkup\n\n```\nIndex           132order_id     400000sales        400000discount     800000region      5350066dtype: int64\n```\n\nThat `region` column, which only has four possible values, is consuming 5.3MB as an `object` type. Convert it to a categorical and watch what happens:\npython\n\n```\ndf['region'] = df['region'].astype('category')\ndf.memory_usage(deep=True)\n```\n\nOutput:\nmarkup\n\n```\nIndex          132order_id    400000sales       400000discount    800000region      100386dtype: int64\n```\n\nFrom 5.3MB down to about 100KB. For one column. The same logic applies to integer columns where you don't need the full `int64` range. If your values fit comfortably in `int32` or even `int16`, downcasting saves real memory.\npython\n\n```\ndf['sales'] = df['sales'].astype('int32')\ndf['order_id'] = df['order_id'].astype('int32')\n\ndf.memory_usage(deep=True)\n```\n\nOutput:\nmarkup\n\n```\nIndex       128order_id    400000sales       400000discount    800000region      100563dtype: int64\n```\n\nA few small type changes and your dataframe is already significantly lighter. And a lighter dataframe means faster operations across the board, because there's simply less data to move around.\n### The Quick Memory Check Habit\nBefore you run any heavy transformation, it's worth knowing what you're working with:\npython\n\n```\nprint(f\"Memory usage: {df.memory_usage(deep=True).sum() / 1024**2:.2f} MB\")\n```\n\nIt takes one second and it tells you exactly how much memory your dataframe is consuming at that point. Make it a habit before and after major transformations and you'll quickly develop an intuition for when something is heavier than it should be.\n### The Insight\nSlow code isn't always about computation. Sometimes your notebook is slow because it's carrying far more data than it needs to, in formats that are far more expensive than necessary. Trimming memory isn't glamorous work, but it compounds. A dataframe that's lighter to store is faster to filter, faster to merge, faster to transform.\nMemory and speed are not separate problems. They're the same problem.\n## Mistake #3: Overusing Pandas for Everything\nThis one is a little different from the previous two. It's not about a specific function or a bad habit. It's about knowing the limits of your tool.\nPandas is genuinely great. For most data tasks, especially at the scale most people are working at, it's more than enough. But there's a version of Pandas usage that I kept seeing described while researching this: people reaching for Pandas by default, for everything, regardless of whether it's the right fit.\nAnd at a certain scale, that becomes a problem.\n### The Dataset\nTo make this real, I generated a synthetic e-commerce dataset with 1 million rows. Nothing exotic, just the kind of data you'd realistically encounter: orders, dates, regions, categories, sales figures, discounts, quantities and statuses.\npython\n\n```\nimport pandas as pd\nimport numpy as np\n\nnp.random.seed(42)\n\nn = 1_000_000\n\nregions = ['north', 'south', 'east', 'west']\ncategories = ['electronics', 'clothing', 'furniture', 'food', 'sports']\nstatuses = ['completed', 'returned', 'pending', 'cancelled']\n\ndf = pd.DataFrame({\n    'order_id': np.arange(1000, 1000 + n),\n    'order_date': pd.date_range(start='2022-01-01', periods=n, freq='1min'),\n    'region': np.random.choice(regions, size=n),\n    'category': np.random.choice(categories, size=n),\n    'sales': np.random.randint(100, 10000, size=n),\n    'quantity': np.random.randint(1, 20, size=n),\n    'discount': np.round(np.random.uniform(0.0, 0.5, size=n), 2),\n    'status': np.random.choice(statuses, size=n),\n})\n\ndf.to_csv('large_sales_data.csv', index=False)\n```\n\nOne million rows. Saved to a CSV. This is the dataset we'll be working with for the rest of the article.\n### Where Pandas Starts to Struggle\nPandas loads your entire dataset into memory. That's fine when your data is a few hundred thousand rows. It starts to get uncomfortable at a few million. And beyond that, you're fighting the tool.\nThe other scenario is complex, nested transformations where you're stacking multiple operations, creating intermediate results, and generally asking Pandas to do a lot of heavy lifting in sequence. Each step adds overhead. The costs stack up.\nHere's a realistic example using our dataset. Say you need to calculate a rolling average of sales per region, flag orders above a threshold, then aggregate by month:\npython\n\n```\n# Step 1: Sort\ndf = df.sort_values(['region', 'order_date'])\n\n# Step 2: Rolling average per region\ndf['rolling_avg'] = (\n    df.groupby('region')['sales']\n    .transform(lambda x: x.rolling(window=7).mean())\n)\n\n# Step 3: Flag high-value orders\ndf['high_value'] = df['sales'] > df['rolling_avg'] * 1.5\n\n# Step 4: Monthly aggregation\ndf['month'] = pd.to_datetime(df['order_date']).dt.to_period('M')\nmonthly_summary = df.groupby(['region', 'month'])['sales'].sum()\n```\n\nThis works. But notice that Step 2 uses `.transform(lambda x: ...)`, which carries the same row-adjacent cost we talked about earlier. On 1 million rows, this pipeline will drag. Go ahead and time it on your machine and you'll see exactly what I mean.\n### What to Reach For Instead\nThe good news is you don't have to abandon Pandas entirely. There are a few options depending on the situation.\n**Chunking**  \nIf your dataset is too large to load all at once, Pandas lets you process it in chunks. Instead of loading all 1 million rows into memory at once, you load and process a portion at a time:\npython\n\n```\nchunk_size = 100_000\nresults = []\n\nfor chunk in pd.read_csv('large_sales_data.csv', chunksize=chunk_size):\n    chunk['discounted_price'] = chunk['sales'] * (1 - chunk['discount'])\n    results.append(chunk.groupby('region')['discounted_price'].sum())\n\nfinal_result = pd.concat(results).groupby(level=0).sum()\nprint(final_result)\n```\n\nInstead of asking Pandas to hold 1 million rows in memory simultaneously, you're feeding it 100,000 rows at a time, processing each chunk, and assembling the results at the end. It's not the most elegant pattern, but it lets you work with data that would otherwise crash your kernel.\n**When to Consider Other Tools**  \nSometimes the honest answer is that Pandas isn't the right tool for the job. This isn't a criticism, it's just scope. A few worth knowing about:\n  * **Polars** : A modern dataframe library built in Rust, designed for speed. It uses lazy evaluation, meaning it optimizes your entire query before executing it. For large datasets it can be dramatically faster than Pandas.\n  * **Dask** : Extends Pandas to work in parallel across multiple cores or even multiple machines. If you're comfortable with Pandas syntax, Dask feels familiar.\n  * **DuckDB** : Lets you run SQL queries directly on your dataframes or CSV files with surprisingly fast performance. Great for aggregations and analytical queries on large data.\n\n\nThe point isn't to abandon Pandas. For most everyday data work, it's the right choice. The point is to recognize when you've hit its ceiling, and know that there are good options on the other side of it.\n## The Real-World Refactor: From 61 Seconds to 0.33 Seconds\nThis is where everything we've covered stops being theoretical.  \nI took our 1 million row e-commerce dataset and wrote the kind of Pandas code that feels completely normal. The kind of thing you'd write on a Tuesday afternoon without thinking twice.\nThen I timed it.\n### The Slow Version\npython\n\n```\nimport time\n\ndf = pd.read_csv('large_sales_data.csv')\n\nstart = time.time()\n\n# Row-wise revenue calculation\ndf['gross_revenue'] = df.apply(\n    lambda row: row['sales'] * row['quantity'], axis=1\n)\ndf['tax'] = df.apply(\n    lambda row: row['gross_revenue'] * 0.075, axis=1\n)\ndf['net_revenue'] = df.apply(\n    lambda row: row['gross_revenue'] - row['tax'], axis=1\n)\n\n# Row-wise flagging\ndf['order_flag'] = df.apply(\n    lambda row: 'high' if row['net_revenue'] > 50000 else 'low', axis=1\n)\n\n# Final aggregation\nresult = df.groupby('region')['net_revenue'].sum()\n\nend = time.time()\nprint(f\"Total runtime: {end - start:.2f} seconds\")\n```\n\nOutput:\nmarkup\n\n```\nTotal runtime: 61.78 seconds\n```\n\nOver a minute. For a four-step pipeline. And nothing looks wrong. Let's break down exactly what's making it slow.\n**Three mistakes, all in one pipeline:**\n  * First, the data types are never addressed. The `region`, `category` and `status` columns load as generic `object` types, which are memory-hungry and slow to work with. We're carrying that dead weight through every single operation.\n  * Second, there are three separate `.apply(axis=1)` calls just to calculate revenue. Each one loops through all 1 million rows in Python, one at a time. We already saw in Section 4 how expensive that is. Here we're doing it three times in a row.\n  * Third, `gross_revenue` and `tax` are created as permanent columns even though they're just intermediate steps. They serve no purpose beyond being stepping stones to `net_revenue`, but they sit in memory for the rest of the pipeline anyway.\n\n\nHere's how I'd fix this step by step\n**Step 1: Fix data types upfront**  \nBefore anything else, convert the obvious categorical columns:\npython\n\n```\ndf['region'] = df['region'].astype('category')\ndf['category'] = df['category'].astype('category')\ndf['status'] = df['status'].astype('category')\n```\n\nThis alone reduces memory usage significantly and makes subsequent operations cheaper across the board.\n**Step 2: Replace**`.apply()`**with vectorized operations**  \nInstead of three separate row-wise calls, one vectorized expression does the same work:\npython\n\n```\n# Before: three .apply() calls, three passes through 1 million rows\ndf['gross_revenue'] = df.apply(lambda row: row['sales'] * row['quantity'], axis=1)\ndf['tax'] = df.apply(lambda row: row['gross_revenue'] * 0.075, axis=1)\ndf['net_revenue'] = df.apply(lambda row: row['gross_revenue'] - row['tax'], axis=1)\n\n# After: one vectorized expression, no temporary columns\ndf['net_revenue'] = df['sales'] * df['quantity'] * (1 - 0.075)\n```\n\n**Step 3: Replace row-wise flagging with**`np.where()`\npython\n\n```\n# Before\ndf['order_flag'] = df.apply(\n    lambda row: 'high' if row['net_revenue'] > 50000 else 'low', axis=1\n)\n\n# After\ndf['order_flag'] = np.where(df['net_revenue'] > 50000, 'high', 'low')\n```\n\nSame logic. Vectorized. Done.\n### The Fast Version\nPut it all together and the pipeline looks like this:\npython\n\n```\nimport time\n\ndf = pd.read_csv('large_sales_data.csv')\n\nstart = time.time()\n\n# Fix 1: Correct data types upfront\ndf['region'] = df['region'].astype('category')\ndf['category'] = df['category'].astype('category')\ndf['status'] = df['status'].astype('category')\n\n# Fix 2: Vectorized revenue calculation, no temporary columns\ndf['net_revenue'] = df['sales'] * df['quantity'] * (1 - 0.075)\n\n# Fix 3: Vectorized flagging with np.where\ndf['order_flag'] = np.where(df['net_revenue'] > 50000, 'high', 'low')\n\n# Final aggregation\nresult = df.groupby('region')['net_revenue'].sum()\n\nend = time.time()\nprint(f\"Total runtime: {end - start:.2f} seconds\")\n```\n\nOutput:\nmarkup\n\n```\nTotal runtime: 0.33 seconds\n```\n\n61.78 seconds down to 0.33 seconds. A **99.5% reduction in runtime**. That's like **187x faster**.\nIt's not a trick. That's just how Pandas is supposed to be used.\n## Before You Run Your Next Notebook\nEverything we covered comes down to a few core habits. Not rules. Not tricks. Just a different way of thinking about your code before you write it.\n  * **Think in columns, not rows.** If you're looping through a dataframe row by row, stop and ask whether the same thing can be expressed as a column operation. Nine times out of ten, it can.\n  * **Measure before you optimize.** Don't guess where the slowness is coming from. Use `%timeit` and `df.memory_usage()` to let the numbers tell you what to fix.\n  * **Watch your memory, not just your speed.** Wrong data types, unnecessary copies and temporary columns all add up. A lighter dataframe is a faster dataframe.\n  * **Know when to switch tools.** Pandas is the right choice most of the time. But at a certain scale, the right optimization is recognizing that you've outgrown it.\n\n\nI started this rabbit hole because I kept seeing the same conversation come up in data communities. People frustrated with slow notebooks, code that worked fine on small data and fell apart on real data. I wanted to understand why.\nWhat I found was that the code wasn't broken. It just wasn't built to scale. And the gap between code that works and code that works efficiently isn't about being an advanced Pandas user. It's about a handful of habits applied consistently.\nIf you've ever waited too long for a notebook to finish and just assumed that was normal, now you know it doesn't have to be.\nIf this changed how you think about your Pandas code, I'd love to hear what bottlenecks you've been dealing with. Feel free to say hi on any of these platforms\n[Medium](https://medium.com/@ibbysalam)\n[LinkedIn](https://www.linkedin.com/in/ibrahim-salami-059863228/)\n[Twitter](https://x.com/IbbySalam)\n[YouTube](https://www.youtube.com/@ibbysalam)\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-542334df68a32cd56c4a.jpeg)\nWritten By\n## [Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\n[See all from Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Pandas](https://towardsdatascience.com/tag/pandas/)[Productivity](https://towardsdatascience.com/tag/productivity/)[Python](https://towardsdatascience.com/tag/python/)[Vectorization](https://towardsdatascience.com/tag/vectorization/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fi-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong%2F&title=I%20Reduced%20My%20Pandas%20Runtime%20by%2095%25%20%E2%80%94%20Here%E2%80%99s%20What%20I%20Was%20Doing%20Wrong)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fi-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong%2F&title=I%20Reduced%20My%20Pandas%20Runtime%20by%2095%25%20%E2%80%94%20Here%E2%80%99s%20What%20I%20Was%20Doing%20Wrong)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fi-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong%2F&text=I%20Reduced%20My%20Pandas%20Runtime%20by%2095%25%20%E2%80%94%20Here%E2%80%99s%20What%20I%20Was%20Doing%20Wrong)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/001.jpg)](https://towardsdatascience.com/5-different-ways-to-save-your-machine-learning-model-b7996489d433/)\n## [5 Different Ways To Save Your Machine Learning Model](https://towardsdatascience.com/5-different-ways-to-save-your-machine-learning-model-b7996489d433/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nSimplifying The Process of Reusing Models\n[Kurtis Pykes](https://towardsdatascience.com/author/kurtispykes/)\nMay 18, 20224 min read\n  * [![](../images/002.jpg)](https://towardsdatascience.com/sql-unit-testing-in-bigquery-here-is-a-tutorial-64fc7a6b377/)\n## [SQL Unit Testing in BigQuery? Here is a tutorial.](https://towardsdatascience.com/sql-unit-testing-in-bigquery-here-is-a-tutorial-64fc7a6b377/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nComplete guide for scripting and UDF testing.\n[Mike Shakhomirov](https://towardsdatascience.com/author/mshakhomirov/)\nDecember 1, 20204 min read\n  * [![](../images/003.jpg)](https://towardsdatascience.com/the-ultimate-data-science-prerequisite-learning-list-348ce89805f9/)\n## [The Ultimate Data Science Prerequisite Learning List](https://towardsdatascience.com/the-ultimate-data-science-prerequisite-learning-list-348ce89805f9/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nSee the best places to learn Linear Algebra, Calculus, Statistics, Probability, and Programming.\n[Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\nOctober 3, 20195 min read\n  * [![](../images/004.jpeg)](https://towardsdatascience.com/how-and-why-performing-one-hot-encoding-in-your-data-science-project-a1500ec72d85/)\n## [How and Why Performing One-Hot Encoding in Your Data Science Project](https://towardsdatascience.com/how-and-why-performing-one-hot-encoding-in-your-data-science-project-a1500ec72d85/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nAn article on what one-hot encoding is, why to use it, and how to do it (in Python)\n[Federico Trotta](https://towardsdatascience.com/author/federicotrotta/)\nJune 27, 20225 min read\n  * [![](../images/005.png)](https://towardsdatascience.com/why-and-how-to-adjust-p-values-in-multiple-hypothesis-testing-2ccf174cdbf8/)\n## [Why and How to Adjust P-values in Multiple Hypothesis Testing](https://towardsdatascience.com/why-and-how-to-adjust-p-values-in-multiple-hypothesis-testing-2ccf174cdbf8/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nP-values below a certain threshold are often used as a method to select relevant features. Advice below suggests how to use them correctly.\n[Igor Šegota](https://towardsdatascience.com/author/igor-s/)\nMay 5, 20239 min read\n  * [![](../images/006.jpg)](https://towardsdatascience.com/args-and-kwargs-in-python-function-calling-made-easy-acfe736f988a/)\n## [Args and Kwargs in Python - Function Calling Made Easy](https://towardsdatascience.com/args-and-kwargs-in-python-function-calling-made-easy-acfe736f988a/)\n[Programming](https://towardsdatascience.com/category/programming/)\nUnderstand how functions can return multiple values in full.\n[Yash Prakash](https://towardsdatascience.com/author/ipom/)\nJanuary 12, 20215 min read\n  * [![](../images/007.jpeg)](https://towardsdatascience.com/the-power-and-danger-of-intuition-in-data-science-bb5c04471f58/)\n## [The Power and Danger of Intuition in Data Science](https://towardsdatascience.com/the-power-and-danger-of-intuition-in-data-science-bb5c04471f58/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nAs I start my new journey as a career Data Scientist, I had to cross paths with my old hypothetical nemesis: The Monty Hall Problem. To...\n[Andrew Mooney](https://towardsdatascience.com/author/andrew-k-mooney/)\nDecember 17, 20208 min read\n  * [![](../images/008.jpg)](https://towardsdatascience.com/bringing-the-best-out-of-jupyter-notebooks-for-data-science-f0871519ca29/)\n## [Bringing the best out of Jupyter Notebooks for Data Science](https://towardsdatascience.com/bringing-the-best-out-of-jupyter-notebooks-for-data-science-f0871519ca29/)\n[Programming](https://towardsdatascience.com/category/programming/)\nEnhance Jupyter Notebook's productivity with these Tips & Tricks.\n[Parul Pandey](https://towardsdatascience.com/author/pandeyparul/)\nDecember 19, 20188 min read\n  * [![](../images/009.jpg)](https://towardsdatascience.com/tsv-in-pandas-a-how-to-guide-1854b4b86c7f/)\n## [TSV in Pandas: A How-To Guide](https://towardsdatascience.com/tsv-in-pandas-a-how-to-guide-1854b4b86c7f/)\n[Programming](https://towardsdatascience.com/category/programming/)\nThe Correct Way of Loading and Writing TSV Files with Pandas\n[Michał Marcińczuk](https://towardsdatascience.com/author/czuk/)\nOctober 1, 20245 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n",
  "metadata": {
    "title": "I Reduced My Pandas Runtime by 95% — Here’s What I Was Doing Wrong | Towards Data Science",
    "description": "Most slow Pandas code \"works\", until it doesn't. Learn how to spot hidden bottlenecks, avoid costly row-wise operations, and know when Pandas is no longer enough.",
    "keywords": null,
    "author": "Ibrahim Salami",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "I Reduced My Pandas Runtime by 95% — Here’s What I Was Doing Wrong",
    "og:description": "Most slow Pandas code \"works\", until it doesn't. Learn how to spot hidden bottlenecks, avoid costly row-wise operations, and know when Pandas is no longer enough.",
    "og:url": "https://towardsdatascience.com/i-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/04/fast-pandas.jpg",
    "og:image:width": "963",
    "og:image:height": "537",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Ibrahim Salami",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "17 min read",
    "article:published_time": "2026-04-26T07:00:10.000Z",
    "article:modified_time": "2026-04-26T07:00:10.000Z",
    "article:author": "https://towardsdatascience.com/author/ibrahim.salami/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_000.txt",
      "chars": 313
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_001.txt",
      "chars": 137
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_002.txt",
      "chars": 10
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_003.txt",
      "chars": 311
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_004.txt",
      "chars": 27
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_005.txt",
      "chars": 67
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_006.txt",
      "chars": 212
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_007.txt",
      "chars": 79
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_008.txt",
      "chars": 67
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_009.txt",
      "chars": 75
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_010.txt",
      "chars": 67
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_011.txt",
      "chars": 60
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_012.txt",
      "chars": 43
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_013.txt",
      "chars": 72
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_014.txt",
      "chars": 184
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_015.txt",
      "chars": 131
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_016.txt",
      "chars": 138
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_017.txt",
      "chars": 162
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_018.txt",
      "chars": 187
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_019.txt",
      "chars": 65
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_020.txt",
      "chars": 56
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_021.txt",
      "chars": 310
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_022.txt",
      "chars": 108
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_023.txt",
      "chars": 74
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_024.txt",
      "chars": 103
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_025.txt",
      "chars": 118
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_026.txt",
      "chars": 100
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_027.txt",
      "chars": 76
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_028.txt",
      "chars": 766
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_029.txt",
      "chars": 462
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_030.txt",
      "chars": 328
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_031.txt",
      "chars": 629
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_032.txt",
      "chars": 29
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_033.txt",
      "chars": 145
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_034.txt",
      "chars": 427
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_035.txt",
      "chars": 191
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_036.txt",
      "chars": 639
    },
    {
      "language": "txt",
      "file": "attachments/02dc776eeb7c/code/block_037.txt",
      "chars": 28
    }
  ],
  "images": [
    {
      "status": "ok",
      "url": "https://cdn-cookieyes.com/assets/images/revisit.svg",
      "bytes": 2339,
      "reused": false,
      "content_type": "image/svg+xml",
      "local_path": "attachments/02dc776eeb7c/images/body-df29beacd7496220cc94.svg",
      "src": "https://cdn-cookieyes.com/assets/images/revisit.svg",
      "alt": "Revisit consent button",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn-cookieyes.com/assets/images/close.svg",
      "bytes": 1345,
      "reused": false,
      "content_type": "image/svg+xml",
      "local_path": "attachments/02dc776eeb7c/images/body-2159bb67f3de8ad870eb.svg",
      "src": "https://cdn-cookieyes.com/assets/images/close.svg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/04/fast-pandas.jpg",
      "bytes": 109140,
      "reused": true,
      "local_path": "attachments/02dc776eeb7c/images/000.jpg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/04/fast-pandas.jpg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/1787657709013_9ddcph.jpeg",
      "bytes": 80178,
      "reused": false,
      "content_type": "image/jpeg",
      "local_path": "attachments/02dc776eeb7c/images/body-542334df68a32cd56c4a.jpeg",
      "src": "https://assets.insightmediagroup.io/media/1787657709013_9ddcph.jpeg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/05/0gY7bB8qDMsUrPY4V-scaled.jpg",
      "bytes": 194207,
      "reused": true,
      "local_path": "attachments/02dc776eeb7c/images/001.jpg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/05/0gY7bB8qDMsUrPY4V-scaled.jpg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/0fxm9-aRVtiE-Jf8A-scaled.jpg",
      "bytes": 231550,
      "reused": true,
      "local_path": "attachments/02dc776eeb7c/images/002.jpg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/0fxm9-aRVtiE-Jf8A-scaled.jpg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2019/10/0bm6EZJ-raqKKCwa5-scaled.jpg",
      "bytes": 326486,
      "reused": true,
      "local_path": "attachments/02dc776eeb7c/images/003.jpg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2019/10/0bm6EZJ-raqKKCwa5-scaled.jpg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/06/1Hnc8dqfWohEPLouJPeFKmw-scaled.jpeg",
      "bytes": 508751,
      "reused": true,
      "local_path": "attachments/02dc776eeb7c/images/004.jpeg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/06/1Hnc8dqfWohEPLouJPeFKmw-scaled.jpeg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/05/1P1LXW8ikCQilW176SdwG5A.png",
      "bytes": 510421,
      "reused": true,
      "local_path": "attachments/02dc776eeb7c/images/005.png",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/05/1P1LXW8ikCQilW176SdwG5A.png",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/07eMcZJedEyHrto_q-scaled.jpg",
      "bytes": 343434,
      "reused": true,
      "local_path": "attachments/02dc776eeb7c/images/006.jpg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/07eMcZJedEyHrto_q-scaled.jpg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/14yK3ntv_rab7QzEPqUAt0Q-scaled.jpeg",
      "bytes": 242773,
      "reused": true,
      "local_path": "attachments/02dc776eeb7c/images/007.jpeg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/14yK3ntv_rab7QzEPqUAt0Q-scaled.jpeg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2018/12/0kFimvWp5vJtxn4ws-scaled.jpg",
      "bytes": 451875,
      "reused": true,
      "local_path": "attachments/02dc776eeb7c/images/008.jpg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2018/12/0kFimvWp5vJtxn4ws-scaled.jpg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/0qh2rDSgO0EIJvK5g-scaled.jpg",
      "bytes": 557759,
      "reused": true,
      "local_path": "attachments/02dc776eeb7c/images/009.jpg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/0qh2rDSgO0EIJvK5g-scaled.jpg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/@ibbysalam",
      "kind": "channel_reference",
      "status": "reference_only"
    },
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/programming/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/ibrahim.salami/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/pandas/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/productivity/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/python/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/vectorization/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/5-different-ways-to-save-your-machine-learning-model-b7996489d433/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/kurtispykes/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/sql-unit-testing-in-bigquery-here-is-a-tutorial-64fc7a6b377/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/mshakhomirov/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/the-ultimate-data-science-prerequisite-learning-list-348ce89805f9/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/computer-science"
    },
    {
      "type": "external",
      "href": "https://medium.com/@ibbysalam"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/ibrahim-salami-059863228/"
    },
    {
      "type": "external",
      "href": "https://x.com/IbbySalam"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/@ibbysalam"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=I+Reduced+My+Pandas+Runtime+by+95%25+%E2%80%94+Here%E2%80%99s+What+I+Was+Doing+Wrong&u=https%3A%2F%2Ftowardsdatascience.com%2Fi-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=I+Reduced+My+Pandas+Runtime+by+95%25+%E2%80%94+Here%E2%80%99s+What+I+Was+Doing+Wrong&url=https%3A%2F%2Ftowardsdatascience.com%2Fi-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=I+Reduced+My+Pandas+Runtime+by+95%25+%E2%80%94+Here%E2%80%99s+What+I+Was+Doing+Wrong&url=https%3A%2F%2Ftowardsdatascience.com%2Fi-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    },
    {
      "type": "external",
      "href": "https://insightmediagroup.io/creator-network"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:33:16Z",
  "source_url": "https://towardsdatascience.com/i-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "http_403",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 13,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Programming](https://towardsdatascience.com/category/programming/)\n# I Reduced My Pandas Runtime by 95% — Here’s What I Was Doing Wrong\nMost slow Pandas code \"works\", until it doesn't. Learn how to spot hidden bottlenecks, avoid costly row-wise operations, and know when Pandas is no longer enough.\n[Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\nApril 26, 202617 min read\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/04/fast-pandas.jpg)\nCreated with Nano Banana\nI've been learning Pandas for some time now. Nothing too crazy though. Just basic data cleaning, exploratory data analysis, and some essential functions. I've also explored things like method chaining for cleaner, more organized code, and operations that silently break your Pandas workflow, both of which I've written about before.\nI never really thought about runtime. Honestly, if my code ran without errors and gave me the output I needed, I was happy. Even if it took a few minutes for all my notebook cells to finish, I didn't care. No errors meant no problems, right?\nThen I came across the concept of vectorization. And something clicked.\nI went down the rabbit hole, as I usually do. The more I read, the more I realized that \"no errors\" and \"efficient code\" are two very different things. Your Pandas code can be completely correct and still be quietly terrible at scale.\nSo this article is me documenting what I found. The mistakes that slow Pandas code down, why they happen, how to fix them, and when Pandas itself might be the bottleneck. If you've ever run a notebook and just assumed the wait time was normal, this one's for you.\nLearn this step by step with the interactive [Computer Science](https://roadmap.sh/computer-science) roadmap.\n## Why \"Working Code\" Isn't Good Enough\nThere's a reason this took me a while to think about. Pandas is designed to be forgiving. You can write code in a dozen different ways and most of them will work. You get your output, your dataframe looks right, and you move on.\nBut that flexibility comes with a hidden cost.\nUnlike SQL or production-grade data systems, Pandas doesn't force you to think about efficiency. It doesn't warn you when you're doing something expensive. It just... does it. Slowly, sometimes. But it does it.\nThink about it this way. SQL has a query optimizer. It looks at what you're asking for and figures out the most efficient way to get it. Pandas doesn't have that. It trusts you to write efficient code. And if you don't know what efficient looks like, you'll never know you're missing it.\nThe result is that a lot of Pandas code in the wild is what I'd call politely inefficient. It works on small datasets. It works on medium datasets with a little patience. But the moment you throw real-world data at it, something that's a few hundred thousand rows or more, the cracks start to show. What used to take seconds now takes minutes. What took minutes becomes unusable.\nAnd the frustrating part is nothing looks wrong. No errors. No warnings. Just a slow notebook and a spinning cursor.\nThat's the trap. Pandas optimizes for convenience, not speed. And convenience is great, until it isn't.\nSo the first shift is a mindset one: working code and efficient code are not the same thing. Once that clicks, everything else follows.\n## Profiling: Stop Guessing, Start Measuring\nHere's something I noticed while going down this rabbit hole. Most people, when they feel like their code is slow, do one of two things. They either rewrite the whole thing from scratch hoping something improves, or they just accept it and wait.\nNeither of those is the right move.\nThe right move is to measure first. You can't optimize what you haven't identified. And more often than not, the part of your code you _think_ is slow isn't actually the problem.\nPandas gives you a few simple tools to start with.\n###  `%timeit` -- Know How Long Things Actually Take\n`%timeit` is a Jupyter magic command that runs a line of code multiple times and gives you the average execution time. It's the simplest way to compare two approaches and know, concretely, which one is faster.\npython\n\n```\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({\n    'sales': np.random.randint(100, 10000, size=100_000),\n    'discount': np.random.uniform(0.0, 0.5, size=100_000)\n})\n\n# Approach A\n%timeit df.apply(lambda row: row['sales'] * row['discount'], axis=1)\n\n# Approach B\n%timeit df['sales'] * df['discount']\n```\n\nOn a dataset of 100,000 rows, the difference is not subtle:\nmarkup\n\n```\n1.91 s ± 228 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)316 μs ± 14 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n```\n\nSame output. Completely different cost. That's the kind of thing you'd never notice by just running the cell once and moving on.\n###  `df.info()` and `df.memory_usage()` -- Know What You're Carrying\nSpeed isn't just about computation. Memory plays a huge role too. A dataframe that's bloated with the wrong data types will slow everything down before you've even written a single transformation.\npython\n\n```\ndf.info()\n```\n\n**Output:**\nmarkup\n\n```\n<class 'pandas.core.frame.DataFrame'>RangeIndex: 100000 entries, 0 to 99999Data columns (total 2 columns): #   Column    Non-Null Count   Dtype  ---  ------    --------------   -----   0   sales     100000 non-null  int64   1   discount  100000 non-null  float64dtypes: float64(1), int64(1)memory usage: 1.5 MB\n```\n\nTo check the memory usage\npython\n\n```\ndf.memory_usage(deep=True)\n```\n\n**Output:**\nmarkup\n\n```\nIndex          132sales       400000discount    800000dtype: int64\n```\n\nHere, we can see that `discount` is taking up twice the space. This is because `discount` is stored as a \"heavier\" number type (`float64`) while `sales` is stored in a \"lighter\" type (`int32`).\nThis becomes especially important when you're working with string columns or object types that are secretly eating memory. We'll come back to this in the next section.\n### The Profiling Mindset\nThe tools themselves are simple. The shift is in how you approach your code. Before you optimize anything, ask: _where is the time actually going?_ Measure the slow parts. Compare alternatives. Let the numbers tell you what to fix.\nBecause what feels slow and what is slow are often two different things entirely.\n## Mistake #1: Row-wise Operations (The Silent Killer)\nIf there's one thing I kept seeing come up again and again while researching this topic, it was this: people looping through Pandas dataframes row by row. And I get it. It feels natural. You think about your data one row at a time, so you write code that processes it one row at a time.\nThe problem is, that's not how Pandas thinks.\n### How Pandas Actually Works\nPandas is built on top of NumPy, which stores data in contiguous blocks of memory, column by column. This means Pandas is heavily optimized to operate on entire columns at once. When you do that, it runs fast, low-level, vectorized operations under the hood.\nWhen you loop through rows instead, you're essentially bypassing all of that. You're dropping down into pure Python, one row at a time, with all the overhead that comes with it. On a small dataset you'll never notice. On a large one, you'll be waiting a long time.\nThere are two patterns that show up constantly.\n### `.iterrows()`\npython\n\n```\n# Calculating a discounted price row by row\ndiscounted_prices = []\n\nfor index, row in df.iterrows():\n    discounted_prices.append(row['sales'] * (1 - row['discount']))\n\ndf['discounted_price'] = discounted_prices\n```\n\n  \nThis works. It will give you the right answer. But on a dataframe with 100,000 rows, it is painfully slow.\npython\n\n```\n%timeit [row['sales'] * (1 - row['discount']) for index, row in df.iterrows()]\n```\n\n**Output:**\nmarkup\n\n```\n10.2 s ± 1.73 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n```\n\n### `.apply(axis=1)`\nThis one is sneakier because it looks more \"Pandas-like.\" But applying a function across axis=1 means applying it row by row, which is essentially the same problem.\npython\n\n```\n%timeit df.apply(lambda row: row['sales'] * (1 - row['discount']), axis=1)\n```\n\n**Output:**\nmarkup\n\n```\n1.5 s ± 88.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n```\n\nFaster than `.iterrows()`, but still operating row by row. Still slow.\n### The Fix: Vectorized Operations\nHere's the same calculation, done the way Pandas actually wants you to do it:\npython\n\n```\ndf['discounted_price'] = df['sales'] * (1 - df['discount'])\n```\n\nLet's time it\npython\n\n```\n%timeit df['sales'] * (1 - df['discount'])\n```\n\nOutput:\nmarkup\n\n```\n688 μs ± 236 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n```\n\nThat's it. One line. No loop. No lambda. And it's roughly **14,800x faster than**`.iterrows()` and **2,180x faster than**`**.apply(axis=1)**`**.**\nWhat's happening here is that Pandas passes the entire column to NumPy, which executes the operation at the C level across the whole array at once. No Python overhead. No row-by-row iteration. Just fast, low-level computation.\n### When `.apply()` Is Actually Fine\nTo be fair, `.apply()` isn't always the villain. When you're applying a function column-wise (axis=0, which is the default), it's often perfectly reasonable. The issue is specifically `axis=1`, which forces row-by-row execution.\nAnd sometimes your logic is genuinely complex enough that a clean vectorized expression isn't obvious. In those cases, `np.vectorize()` or `np.where()` can give you something closer to vectorized performance while still letting you express conditional logic clearly.\npython\n\n```\n# Instead of this\ndf['category'] = df.apply(\n    lambda row: 'high' if row['sales'] > 5000 else 'low', axis=1\n)\n\n# Do this\ndf['category'] = np.where(df['sales'] > 5000, 'high', 'low')\n```\n\npython\n\n```\n%timeit df.apply(lambda row: 'high' if row['sales'] > 5000 else 'low', axis=1)\n%timeit np.where(df['sales'] > 5000, 'high', 'low')\n```\n\nOutput:\nmarkup\n\n```\n1.31 s ± 189 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)1.3 ms ± 180 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n```\n\nSame result. About **1,000x faster**.\n### The Rule of Thumb\nIf you're writing a loop over rows in Pandas, stop and ask yourself: can this be expressed as a column operation? Nine times out of ten, the answer is yes. And when it is, the performance difference is transformative.\nIf you're looping through rows, you're not using Pandas. You're using Python with extra steps.\n## Mistake #2: Unnecessary Copies and Memory Bloat\nRow-wise operations get a lot of attention when people talk about Pandas performance. Memory gets a lot less. Which is a shame, because in my experience reading about this, bloated memory is just as responsible for slow notebooks as bad computation.\nHere's the thing. Pandas operations don't always modify your dataframe in place. A lot of them quietly create a brand new copy of your data behind the scenes. Do that enough times, and you're not just holding one dataframe in memory. You're holding several, all at once, without realizing it.\n### The Hidden Cost of Chained Operations\nChained operations are a common culprit. They look clean and readable, but each step can generate an intermediate copy that sits in memory until garbage collection cleans it up.\npython\n\n```\n# Each step here potentially creates a new copy\ndf2 = df[df['sales'] > 1000]\ndf3 = df2.dropna()\ndf4 = df3.reset_index(drop=True)\ndf5 = df4[['sales', 'discount']]\n```\n\nBy the time you get to `df5`, you potentially have five versions of your data floating around in memory simultaneously. On a small dataset this is invisible. On a large one, this is how you run out of RAM.\n### Temporary Columns That Stick Around\nAnother pattern that quietly eats memory is creating columns you only needed temporarily.\npython\n\n```\ndf['gross_revenue'] = df['sales'] * df['quantity']\ndf['tax'] = df['gross_revenue'] * 0.075\ndf['net_revenue'] = df['gross_revenue'] - df['tax']\n\n# But you only actually needed net_revenue\n```\n\n`gross_revenue` and `tax` are now permanent columns in your dataframe, taking up memory for the rest of your notebook even though they were just stepping stones.\nThe fix is simple. Either compute directly:\npython\n\n```\ndf['net_revenue'] = (df['sales'] * df['quantity']) * (1 - 0.075)\n```\n\nOr drop them as soon as you're done:\npython\n\n```\ndf.drop(columns=['gross_revenue', 'tax'], inplace=True)\n```\n\n### Wrong Data Types Are Quietly Expensive\nThis one surprised me when I came across it. By default, Pandas is quite generous with how much memory it assigns to each column. Integer columns get `int64`. Float columns get `float64`. String columns become `object` type, which is one of the most memory-hungry types in Pandas.\nLet's see what that actually looks like:\npython\n\n```\ndf = pd.DataFrame({\n    'order_id': np.random.randint(1000, 9999, size=100_000),\n    'sales': np.random.randint(100, 10000, size=100_000),\n    'discount': np.random.uniform(0.0, 0.5, size=100_000),\n    'region': np.random.choice(['north', 'south', 'east', 'west'], size=100_000)\n})\n\ndf.memory_usage(deep=True)\n```\n\nOutput\nmarkup\n\n```\nIndex           132order_id     400000sales        400000discount     800000region      5350066dtype: int64\n```\n\nThat `region` column, which only has four possible values, is consuming 5.3MB as an `object` type. Convert it to a categorical and watch what happens:\npython\n\n```\ndf['region'] = df['region'].astype('category')\ndf.memory_usage(deep=True)\n```\n\nOutput:\nmarkup\n\n```\nIndex          132order_id    400000sales       400000discount    800000region      100386dtype: int64\n```\n\nFrom 5.3MB down to about 100KB. For one column. The same logic applies to integer columns where you don't need the full `int64` range. If your values fit comfortably in `int32` or even `int16`, downcasting saves real memory.\npython\n\n```\ndf['sales'] = df['sales'].astype('int32')\ndf['order_id'] = df['order_id'].astype('int32')\n\ndf.memory_usage(deep=True)\n```\n\nOutput:\nmarkup\n\n```\nIndex       128order_id    400000sales       400000discount    800000region      100563dtype: int64\n```\n\nA few small type changes and your dataframe is already significantly lighter. And a lighter dataframe means faster operations across the board, because there's simply less data to move around.\n### The Quick Memory Check Habit\nBefore you run any heavy transformation, it's worth knowing what you're working with:\npython\n\n```\nprint(f\"Memory usage: {df.memory_usage(deep=True).sum() / 1024**2:.2f} MB\")\n```\n\nIt takes one second and it tells you exactly how much memory your dataframe is consuming at that point. Make it a habit before and after major transformations and you'll quickly develop an intuition for when something is heavier than it should be.\n### The Insight\nSlow code isn't always about computation. Sometimes your notebook is slow because it's carrying far more data than it needs to, in formats that are far more expensive than necessary. Trimming memory isn't glamorous work, but it compounds. A dataframe that's lighter to store is faster to filter, faster to merge, faster to transform.\nMemory and speed are not separate problems. They're the same problem.\n## Mistake #3: Overusing Pandas for Everything\nThis one is a little different from the previous two. It's not about a specific function or a bad habit. It's about knowing the limits of your tool.\nPandas is genuinely great. For most data tasks, especially at the scale most people are working at, it's more than enough. But there's a version of Pandas usage that I kept seeing described while researching this: people reaching for Pandas by default, for everything, regardless of whether it's the right fit.\nAnd at a certain scale, that becomes a problem.\n### The Dataset\nTo make this real, I generated a synthetic e-commerce dataset with 1 million rows. Nothing exotic, just the kind of data you'd realistically encounter: orders, dates, regions, categories, sales figures, discounts, quantities and statuses.\npython\n\n```\nimport pandas as pd\nimport numpy as np\n\nnp.random.seed(42)\n\nn = 1_000_000\n\nregions = ['north', 'south', 'east', 'west']\ncategories = ['electronics', 'clothing', 'furniture', 'food', 'sports']\nstatuses = ['completed', 'returned', 'pending', 'cancelled']\n\ndf = pd.DataFrame({\n    'order_id': np.arange(1000, 1000 + n),\n    'order_date': pd.date_range(start='2022-01-01', periods=n, freq='1min'),\n    'region': np.random.choice(regions, size=n),\n    'category': np.random.choice(categories, size=n),\n    'sales': np.random.randint(100, 10000, size=n),\n    'quantity': np.random.randint(1, 20, size=n),\n    'discount': np.round(np.random.uniform(0.0, 0.5, size=n), 2),\n    'status': np.random.choice(statuses, size=n),\n})\n\ndf.to_csv('large_sales_data.csv', index=False)\n```\n\nOne million rows. Saved to a CSV. This is the dataset we'll be working with for the rest of the article.\n### Where Pandas Starts to Struggle\nPandas loads your entire dataset into memory. That's fine when your data is a few hundred thousand rows. It starts to get uncomfortable at a few million. And beyond that, you're fighting the tool.\nThe other scenario is complex, nested transformations where you're stacking multiple operations, creating intermediate results, and generally asking Pandas to do a lot of heavy lifting in sequence. Each step adds overhead. The costs stack up.\nHere's a realistic example using our dataset. Say you need to calculate a rolling average of sales per region, flag orders above a threshold, then aggregate by month:\npython\n\n```\n# Step 1: Sort\ndf = df.sort_values(['region', 'order_date'])\n\n# Step 2: Rolling average per region\ndf['rolling_avg'] = (\n    df.groupby('region')['sales']\n    .transform(lambda x: x.rolling(window=7).mean())\n)\n\n# Step 3: Flag high-value orders\ndf['high_value'] = df['sales'] > df['rolling_avg'] * 1.5\n\n# Step 4: Monthly aggregation\ndf['month'] = pd.to_datetime(df['order_date']).dt.to_period('M')\nmonthly_summary = df.groupby(['region', 'month'])['sales'].sum()\n```\n\nThis works. But notice that Step 2 uses `.transform(lambda x: ...)`, which carries the same row-adjacent cost we talked about earlier. On 1 million rows, this pipeline will drag. Go ahead and time it on your machine and you'll see exactly what I mean.\n### What to Reach For Instead\nThe good news is you don't have to abandon Pandas entirely. There are a few options depending on the situation.\n**Chunking**  \nIf your dataset is too large to load all at once, Pandas lets you process it in chunks. Instead of loading all 1 million rows into memory at once, you load and process a portion at a time:\npython\n\n```\nchunk_size = 100_000\nresults = []\n\nfor chunk in pd.read_csv('large_sales_data.csv', chunksize=chunk_size):\n    chunk['discounted_price'] = chunk['sales'] * (1 - chunk['discount'])\n    results.append(chunk.groupby('region')['discounted_price'].sum())\n\nfinal_result = pd.concat(results).groupby(level=0).sum()\nprint(final_result)\n```\n\nInstead of asking Pandas to hold 1 million rows in memory simultaneously, you're feeding it 100,000 rows at a time, processing each chunk, and assembling the results at the end. It's not the most elegant pattern, but it lets you work with data that would otherwise crash your kernel.\n**When to Consider Other Tools**  \nSometimes the honest answer is that Pandas isn't the right tool for the job. This isn't a criticism, it's just scope. A few worth knowing about:\n  * **Polars** : A modern dataframe library built in Rust, designed for speed. It uses lazy evaluation, meaning it optimizes your entire query before executing it. For large datasets it can be dramatically faster than Pandas.\n  * **Dask** : Extends Pandas to work in parallel across multiple cores or even multiple machines. If you're comfortable with Pandas syntax, Dask feels familiar.\n  * **DuckDB** : Lets you run SQL queries directly on your dataframes or CSV files with surprisingly fast performance. Great for aggregations and analytical queries on large data.\n\n\nThe point isn't to abandon Pandas. For most everyday data work, it's the right choice. The point is to recognize when you've hit its ceiling, and know that there are good options on the other side of it.\n## The Real-World Refactor: From 61 Seconds to 0.33 Seconds\nThis is where everything we've covered stops being theoretical.  \nI took our 1 million row e-commerce dataset and wrote the kind of Pandas code that feels completely normal. The kind of thing you'd write on a Tuesday afternoon without thinking twice.\nThen I timed it.\n### The Slow Version\npython\n\n```\nimport time\n\ndf = pd.read_csv('large_sales_data.csv')\n\nstart = time.time()\n\n# Row-wise revenue calculation\ndf['gross_revenue'] = df.apply(\n    lambda row: row['sales'] * row['quantity'], axis=1\n)\ndf['tax'] = df.apply(\n    lambda row: row['gross_revenue'] * 0.075, axis=1\n)\ndf['net_revenue'] = df.apply(\n    lambda row: row['gross_revenue'] - row['tax'], axis=1\n)\n\n# Row-wise flagging\ndf['order_flag'] = df.apply(\n    lambda row: 'high' if row['net_revenue'] > 50000 else 'low', axis=1\n)\n\n# Final aggregation\nresult = df.groupby('region')['net_revenue'].sum()\n\nend = time.time()\nprint(f\"Total runtime: {end - start:.2f} seconds\")\n```\n\nOutput:\nmarkup\n\n```\nTotal runtime: 61.78 seconds\n```\n\nOver a minute. For a four-step pipeline. And nothing looks wrong. Let's break down exactly what's making it slow.\n**Three mistakes, all in one pipeline:**\n  * First, the data types are never addressed. The `region`, `category` and `status` columns load as generic `object` types, which are memory-hungry and slow to work with. We're carrying that dead weight through every single operation.\n  * Second, there are three separate `.apply(axis=1)` calls just to calculate revenue. Each one loops through all 1 million rows in Python, one at a time. We already saw in Section 4 how expensive that is. Here we're doing it three times in a row.\n  * Third, `gross_revenue` and `tax` are created as permanent columns even though they're just intermediate steps. They serve no purpose beyond being stepping stones to `net_revenue`, but they sit in memory for the rest of the pipeline anyway.\n\n\nHere's how I'd fix this step by step\n**Step 1: Fix data types upfront**  \nBefore anything else, convert the obvious categorical columns:\npython\n\n```\ndf['region'] = df['region'].astype('category')\ndf['category'] = df['category'].astype('category')\ndf['status'] = df['status'].astype('category')\n```\n\nThis alone reduces memory usage significantly and makes subsequent operations cheaper across the board.\n**Step 2: Replace**`.apply()`**with vectorized operations**  \nInstead of three separate row-wise calls, one vectorized expression does the same work:\npython\n\n```\n# Before: three .apply() calls, three passes through 1 million rows\ndf['gross_revenue'] = df.apply(lambda row: row['sales'] * row['quantity'], axis=1)\ndf['tax'] = df.apply(lambda row: row['gross_revenue'] * 0.075, axis=1)\ndf['net_revenue'] = df.apply(lambda row: row['gross_revenue'] - row['tax'], axis=1)\n\n# After: one vectorized expression, no temporary columns\ndf['net_revenue'] = df['sales'] * df['quantity'] * (1 - 0.075)\n```\n\n**Step 3: Replace row-wise flagging with**`np.where()`\npython\n\n```\n# Before\ndf['order_flag'] = df.apply(\n    lambda row: 'high' if row['net_revenue'] > 50000 else 'low', axis=1\n)\n\n# After\ndf['order_flag'] = np.where(df['net_revenue'] > 50000, 'high', 'low')\n```\n\nSame logic. Vectorized. Done.\n### The Fast Version\nPut it all together and the pipeline looks like this:\npython\n\n```\nimport time\n\ndf = pd.read_csv('large_sales_data.csv')\n\nstart = time.time()\n\n# Fix 1: Correct data types upfront\ndf['region'] = df['region'].astype('category')\ndf['category'] = df['category'].astype('category')\ndf['status'] = df['status'].astype('category')\n\n# Fix 2: Vectorized revenue calculation, no temporary columns\ndf['net_revenue'] = df['sales'] * df['quantity'] * (1 - 0.075)\n\n# Fix 3: Vectorized flagging with np.where\ndf['order_flag'] = np.where(df['net_revenue'] > 50000, 'high', 'low')\n\n# Final aggregation\nresult = df.groupby('region')['net_revenue'].sum()\n\nend = time.time()\nprint(f\"Total runtime: {end - start:.2f} seconds\")\n```\n\nOutput:\nmarkup\n\n```\nTotal runtime: 0.33 seconds\n```\n\n61.78 seconds down to 0.33 seconds. A **99.5% reduction in runtime**. That's like **187x faster**.\nIt's not a trick. That's just how Pandas is supposed to be used.\n## Before You Run Your Next Notebook\nEverything we covered comes down to a few core habits. Not rules. Not tricks. Just a different way of thinking about your code before you write it.\n  * **Think in columns, not rows.** If you're looping through a dataframe row by row, stop and ask whether the same thing can be expressed as a column operation. Nine times out of ten, it can.\n  * **Measure before you optimize.** Don't guess where the slowness is coming from. Use `%timeit` and `df.memory_usage()` to let the numbers tell you what to fix.\n  * **Watch your memory, not just your speed.** Wrong data types, unnecessary copies and temporary columns all add up. A lighter dataframe is a faster dataframe.\n  * **Know when to switch tools.** Pandas is the right choice most of the time. But at a certain scale, the right optimization is recognizing that you've outgrown it.\n\n\nI started this rabbit hole because I kept seeing the same conversation come up in data communities. People frustrated with slow notebooks, code that worked fine on small data and fell apart on real data. I wanted to understand why.\nWhat I found was that the code wasn't broken. It just wasn't built to scale. And the gap between code that works and code that works efficiently isn't about being an advanced Pandas user. It's about a handful of habits applied consistently.\nIf you've ever waited too long for a notebook to finish and just assumed that was normal, now you know it doesn't have to be.\nIf this changed how you think about your Pandas code, I'd love to hear what bottlenecks you've been dealing with. Feel free to say hi on any of these platforms\n[Medium](https://medium.com/@ibbysalam)\n[LinkedIn](https://www.linkedin.com/in/ibrahim-salami-059863228/)\n[Twitter](https://x.com/IbbySalam)\n[YouTube](https://www.youtube.com/@ibbysalam)\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657709013_9ddcph.jpeg)\nWritten By\n## [Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\n[See all from Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Pandas](https://towardsdatascience.com/tag/pandas/)[Productivity](https://towardsdatascience.com/tag/productivity/)[Python](https://towardsdatascience.com/tag/python/)[Vectorization](https://towardsdatascience.com/tag/vectorization/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fi-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong%2F&title=I%20Reduced%20My%20Pandas%20Runtime%20by%2095%25%20%E2%80%94%20Here%E2%80%99s%20What%20I%20Was%20Doing%20Wrong)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fi-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong%2F&title=I%20Reduced%20My%20Pandas%20Runtime%20by%2095%25%20%E2%80%94%20Here%E2%80%99s%20What%20I%20Was%20Doing%20Wrong)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fi-reduced-my-pandas-runtime-by-95-heres-what-i-was-doing-wrong%2F&text=I%20Reduced%20My%20Pandas%20Runtime%20by%2095%25%20%E2%80%94%20Here%E2%80%99s%20What%20I%20Was%20Doing%20Wrong)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/05/0gY7bB8qDMsUrPY4V-scaled.jpg)](https://towardsdatascience.com/5-different-ways-to-save-your-machine-learning-model-b7996489d433/)\n## [5 Different Ways To Save Your Machine Learning Model](https://towardsdatascience.com/5-different-ways-to-save-your-machine-learning-model-b7996489d433/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nSimplifying The Process of Reusing Models\n[Kurtis Pykes](https://towardsdatascience.com/author/kurtispykes/)\nMay 18, 20224 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/0fxm9-aRVtiE-Jf8A-scaled.jpg)](https://towardsdatascience.com/sql-unit-testing-in-bigquery-here-is-a-tutorial-64fc7a6b377/)\n## [SQL Unit Testing in BigQuery? Here is a tutorial.](https://towardsdatascience.com/sql-unit-testing-in-bigquery-here-is-a-tutorial-64fc7a6b377/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nComplete guide for scripting and UDF testing.\n[Mike Shakhomirov](https://towardsdatascience.com/author/mshakhomirov/)\nDecember 1, 20204 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2019/10/0bm6EZJ-raqKKCwa5-scaled.jpg)](https://towardsdatascience.com/the-ultimate-data-science-prerequisite-learning-list-348ce89805f9/)\n## [The Ultimate Data Science Prerequisite Learning List](https://towardsdatascience.com/the-ultimate-data-science-prerequisite-learning-list-348ce89805f9/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nSee the best places to learn Linear Algebra, Calculus, Statistics, Probability, and Programming.\n[Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\nOctober 3, 20195 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/06/1Hnc8dqfWohEPLouJPeFKmw-scaled.jpeg)](https://towardsdatascience.com/how-and-why-performing-one-hot-encoding-in-your-data-science-project-a1500ec72d85/)\n## [How and Why Performing One-Hot Encoding in Your Data Science Project](https://towardsdatascience.com/how-and-why-performing-one-hot-encoding-in-your-data-science-project-a1500ec72d85/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nAn article on what one-hot encoding is, why to use it, and how to do it (in Python)\n[Federico Trotta](https://towardsdatascience.com/author/federicotrotta/)\nJune 27, 20225 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/05/1P1LXW8ikCQilW176SdwG5A.png)](https://towardsdatascience.com/why-and-how-to-adjust-p-values-in-multiple-hypothesis-testing-2ccf174cdbf8/)\n## [Why and How to Adjust P-values in Multiple Hypothesis Testing](https://towardsdatascience.com/why-and-how-to-adjust-p-values-in-multiple-hypothesis-testing-2ccf174cdbf8/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nP-values below a certain threshold are often used as a method to select relevant features. Advice below suggests how to use them correctly.\n[Igor Šegota](https://towardsdatascience.com/author/igor-s/)\nMay 5, 20239 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/07eMcZJedEyHrto_q-scaled.jpg)](https://towardsdatascience.com/args-and-kwargs-in-python-function-calling-made-easy-acfe736f988a/)\n## [Args and Kwargs in Python - Function Calling Made Easy](https://towardsdatascience.com/args-and-kwargs-in-python-function-calling-made-easy-acfe736f988a/)\n[Programming](https://towardsdatascience.com/category/programming/)\nUnderstand how functions can return multiple values in full.\n[Yash Prakash](https://towardsdatascience.com/author/ipom/)\nJanuary 12, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/14yK3ntv_rab7QzEPqUAt0Q-scaled.jpeg)](https://towardsdatascience.com/the-power-and-danger-of-intuition-in-data-science-bb5c04471f58/)\n## [The Power and Danger of Intuition in Data Science](https://towardsdatascience.com/the-power-and-danger-of-intuition-in-data-science-bb5c04471f58/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nAs I start my new journey as a career Data Scientist, I had to cross paths with my old hypothetical nemesis: The Monty Hall Problem. To...\n[Andrew Mooney](https://towardsdatascience.com/author/andrew-k-mooney/)\nDecember 17, 20208 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2018/12/0kFimvWp5vJtxn4ws-scaled.jpg)](https://towardsdatascience.com/bringing-the-best-out-of-jupyter-notebooks-for-data-science-f0871519ca29/)\n## [Bringing the best out of Jupyter Notebooks for Data Science](https://towardsdatascience.com/bringing-the-best-out-of-jupyter-notebooks-for-data-science-f0871519ca29/)\n[Programming](https://towardsdatascience.com/category/programming/)\nEnhance Jupyter Notebook's productivity with these Tips & Tricks.\n[Parul Pandey](https://towardsdatascience.com/author/pandeyparul/)\nDecember 19, 20188 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/10/0qh2rDSgO0EIJvK5g-scaled.jpg)](https://towardsdatascience.com/tsv-in-pandas-a-how-to-guide-1854b4b86c7f/)\n## [TSV in Pandas: A How-To Guide](https://towardsdatascience.com/tsv-in-pandas-a-how-to-guide-1854b4b86c7f/)\n[Programming](https://towardsdatascience.com/category/programming/)\nThe Correct Way of Loading and Writing TSV Files with Pandas\n[Michał Marcińczuk](https://towardsdatascience.com/author/czuk/)\nOctober 1, 20245 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n",
  "body_base_path": "attachments/02dc776eeb7c/pages/",
  "body_markdown_path": "attachments/02dc776eeb7c/pages/archived-body.md",
  "local_html": "attachments/02dc776eeb7c/pages/archived-body.html",
  "body_source": "prior_capture"
}