Overview

12 Performance

The chapter introduces pandas performance as a practical concern: modern computers are powerful, but large data sets can still feel slow and memory-hungry. The central idea is that pandas works best when you keep data slim, stay as much as possible in NumPy-like structures, and measure both memory use and execution time before optimizing. It emphasizes that performance work is often about using only the columns you need, choosing efficient data types, and understanding what pandas is doing behind the scenes.

A major focus is memory reduction through categorical data. The text shows how to inspect memory with memory_usage and why a deep check is necessary to count Python string objects accurately. It then demonstrates converting repeated text columns into categories, which stores each distinct string once and replaces repeated values with compact internal codes. Using this approach on the Olympics data dramatically cuts memory usage, and the chapter explains how to identify the best candidate columns by looking for repeated values, as well as how to define categories ahead of time when future values are expected.

The chapter also explores faster reading and writing with Apache Arrow and its feather format, showing that binary formats can be much smaller and quicker than CSV or JSON for both saving and loading. It then shifts to query performance, comparing traditional boolean indexing with query, eval, and related tools. The takeaway is that query and eval can reduce temporary objects and speed up complex expressions, especially on large data sets, while isin is often the best choice for membership tests. Overall, the chapter encourages careful benchmarking and choosing the right tool for the data size, query complexity, and storage format involved.

Summary

Calculations and analysis with pandas are much faster than they would be in pure Python. Even so, when you’re working with a large data set, you’ll often want or need to reduce the memory footprint of your data frame and use techniques that can improve performance. In this chapter, we reviewed a number of techniques you can use to speed up your queries and also use fewer resources:

  • Choosing columns carefully
  • Reducing memory usage with categories
  • Reading data from feather format rather than CSV
  • Speeding up complex queries with df.query and df.eval

If you’ve reached this part of the book, congratulations! You’ve successfully gone through all 50 exercises! I have no doubt that if you’ve made it this far, you have a much better, deeper understanding of pandas, what it can do, and how you can use it in a variety of situations. You should feel good about yourself and confident about your ability to use pandas at work.

But before you stop reading: the next chapter contains a large project in which I’ll ask you to use all the techniques from this book to analyze a large real-world data set. I hope you’ll take the time to do the project, which will help cement the lessons you’ve learned and help you use pandas even more effectively in the future.

FAQ

What is the main goal of Chapter 12 on performance?Chapter 12 focuses on making pandas work faster and use less memory. It covers measuring memory usage, timing code, reducing data-frame size, using categories, and speeding up file I/O and queries with tools like PyArrow, query, and eval.
Why can pandas memory usage reports be misleading?By default, pandas does not count the full memory taken by Python objects stored in object columns, such as strings. As a result, df.memory_usage() can underreport actual usage unless you pass deep=True.
How do you get an accurate memory usage total for a DataFrame?Use df.memory_usage(deep=True).sum() or df.info(memory_usage='deep'). These methods force pandas to include the true memory cost of object values.
What is a category in pandas, and why does it help performance?A category stores repeated string values once and represents them with smaller integer codes. This can greatly reduce memory usage, especially for columns with many repeated values, while still behaving much like a string column.
How do you convert a column to a categorical type?You can use df['colname'] = df['colname'].astype('category'). If you need a predefined set of allowed values, you can first create a pd.CategoricalDtype and then cast the column to that type.
Which columns are best candidates for conversion to categories?Columns with many repeated values are usually the best candidates. A useful heuristic is to look at the ratio of non-null values to unique values, such as (df.count() / df.nunique()).sort_values(ascending=False), and prioritize the highest ratios.
Why can converting to categories save so much memory in the Olympics example?The Olympics data has many repeated text values, especially in columns like Games, Sport, Team, and others. Turning those repeated strings into categories replaces many duplicate string objects with compact integer codes, cutting memory dramatically.
How do PyArrow and feather improve pandas performance?PyArrow provides a fast, efficient data storage and processing layer. Feather, an Apache Arrow format, is a binary format that is smaller and faster to read and write than CSV or JSON, making it a strong choice for repeated storage and loading of data.
When should you use df.query instead of df.loc?df.query is often useful for large data frames and complex conditions, especially when combining conditions with & or |. It can use less memory and sometimes run faster than df.loc, though df.loc is often more flexible and can be faster for simpler cases.
What is the difference between df.query, df.eval, and pd.eval?df.query is mainly for selecting rows. df.eval can evaluate expressions, filter conditions, and perform assignments on a single DataFrame. pd.eval works at the top level and can handle expressions involving multiple data frames, but its syntax is less convenient.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Pandas Workout Pandas Workout ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Pandas Workout Pandas Workout ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Pandas Workout Pandas Workout ebook for free