Sub topic 9
Measuring memory and speed
This chapter assumes you can create a Series, know what a dtype is, and have seen the string dtype and .str accessor from earlier chapters. Here you will measure how much memory a text column uses and how long an operation takes, so you can choose a representation from data rather than from guesses.
Why measure
Text columns can be large. Each value in an object column is a separate Python string, and the column stores a pointer to each one. The string dtype with the pyarrow backend packs the characters into one contiguous buffer instead. Which layout is smaller or faster depends on your data, your pandas version, and the operation, so measure on your own data.
Memory with memory_usage(deep=True)
Series.memory_usage() reports only the pointer array for an object column unless you pass deep=True. With deep=True, pandas also counts the Python string objects the pointers refer to.
import pandas as pd
values = ["red", "green", "blue"] * 1000
obj = pd.Series(values, dtype=object)
py = pd.Series(values, dtype=pd.StringDtype("python"))
pa = pd.Series(values, dtype=pd.StringDtype("pyarrow")) # needs pyarrow installed
print("shallow object:", obj.memory_usage())
print("deep object: ", obj.memory_usage(deep=True))
print("python string: ", py.memory_usage(deep=True))
print("pyarrow string:", pa.memory_usage(deep=True))Compare the shallow and deep numbers for obj. The shallow figure is far too low for text. Always use deep=True when you compare text columns.
Speed with repeated timing
A single timing is noisy. Run the operation several times and keep the fastest result, which is the one least disturbed by other work on the machine.
import time
import pandas as pd
values = ["alpha", "beta", "gamma", "delta"] * 250_000
def best_time(func, repeats=5):
best = float("inf")
for _ in range(repeats):
start = time.perf_counter()
func()
best = min(best, time.perf_counter() - start)
return best
obj = pd.Series(values, dtype=object)
py = pd.Series(values, dtype=pd.StringDtype("python"))
pa = pd.Series(values, dtype=pd.StringDtype("pyarrow"))
for name, s in [("object", obj), ("python", py), ("pyarrow", pa)]:
t = best_time(lambda: s.str.upper())
print(f"{name:8s} upper: {t:.4f} s")The same loop works for str.contains, str.split, or any other step in your pipeline. Time the operation you actually run, because results differ between operations. Also include the cost of conversion if your pipeline pays it once per run.
What to compare
Measure each candidate representation on the same values and record three things.
| Measure | How | What it tells you |
|---|---|---|
| Memory | `memory_usage(deep=True)` | Whether the column fits comfortably in RAM |
| Speed | Best of several `time.perf_counter()` runs | Cost of the operations you repeat |
| Conversion cost | Time `astype(...)` once | Whether switching pays for itself |
The usual pattern is that the pyarrow backend uses less memory than object for large text columns, and it often runs string operations faster. The gap varies with string length, the number of repeated values, and the operation. Small columns show little difference, so test at a realistic size.
Category as a third candidate
If a column has few distinct values, category stores each distinct string once and keeps an integer code per row.
import pandas as pd
s = pd.Series(["a", "b", "a", "b"] * 1000, dtype="string")
cat = s.astype("category")
print(s.memory_usage(deep=True))
print(cat.memory_usage(deep=True))Add category to your comparison whenever the ratio of distinct values to rows is low. The next chapter covers when it wins and what you give up.
Common measurement errors
- Reading
memory_usage()withoutdeep=Trueon anobjectcolumn, which understates the real size. - Timing one run, so the result reflects a cold cache or background load.
- Testing with a tiny Series, where fixed overhead hides the real difference.
- Comparing dtypes built from different data, so the strings themselves differ.
- Forgetting that the
pyarrowbackend needs thepyarrowpackage, and that results on one machine and version may not carry over to another.
Exercise
You compare an object column and a pyarrow string column of the same 5 million values. You call memory_usage() on both and the object column looks much smaller. What did you most likely do wrong, and how do you fix it?
Show answer
You left out deep=True. Without it, an object column reports only its array of pointers and ignores the Python string objects. Call memory_usage(deep=True) on both Series so the string contents are counted, then compare again.
Exercise
Why does the timing helper in this chapter keep the minimum of several runs instead of the average?
Show answer
Other processes and cache effects can only make a run slower, never faster than the code's true cost. The minimum is therefore the least disturbed measurement, while the average includes that noise.