Sub topic 8
Choosing a storage backend
This chapter assumes you can build Series and DataFrames, know what a dtype is, and have met dtype="string" and pd.NA in the earlier chapters. Here you learn what "storage" means for the string dtype, how the two backends differ, and how to choose one.
One dtype, two storage engines
The string dtype is a contract about behavior. Missing values are pd.NA, .str methods return nullable results, and only strings are allowed. The storage backend decides how the characters are held in memory.
pythonstorage keeps a NumPy array of Pythonstrobjects, the same layout as anobjectcolumn. Each element is a separate Python object, and a pointer in the array refers to it.pyarrowstorage keeps the text in an Apache Arrow array. All the UTF-8 bytes sit in one contiguous buffer. A second buffer records where each string starts, and a bitmap records which entries are missing.
You select a backend with the storage argument of pd.StringDtype. The string aliases "string[python]" and "string[pyarrow]" do the same thing.
import pandas as pd
values = ["red", "green", None, "blue"]
py = pd.Series(values, dtype=pd.StringDtype("python"))
pa = pd.Series(values, dtype=pd.StringDtype("pyarrow"))
print(py.dtype, py.dtype.storage)
print(pa.dtype, pa.dtype.storage)
print(py.isna().tolist() == pa.isna().tolist())The pyarrow backend needs the pyarrow package. Without it, pd.StringDtype("pyarrow") raises an ImportError.
What is the same on both backends
Both backends implement the same string dtype, so the behavior you rely on in everyday code does not change.
- Missing entries are
pd.NA, andisna()reports them. - Comparisons and
.str.containsreturn the nullablebooleandtype. .strhas the same method names and arguments.- Results can be assigned back into DataFrames and used in
groupby,merge, andsort_values.
In most analysis code you can switch the backend and see identical output. The differences are in memory, speed, and a few edge cases. They are covered below.
What differs
| Aspect | `python` storage | `pyarrow` storage |
|---|---|---|
| Internal layout | NumPy object array of `str` objects | Arrow buffers: bytes, offsets, validity bitmap |
| Extra dependency | None | `pyarrow` |
| Memory per value | Pointer plus a full Python object, about 50 bytes of overhead each | Bytes plus a 4 or 8 byte offset, with a bit for missingness |
| Vectorized `.str` methods | Python loop over the elements | Arrow compute kernels for many methods |
| Regex engine | Python `re` | RE2 for methods that run in Arrow |
| Element-wise assignment | Cheap | Slower, because Arrow arrays are immutable |
| Conversion to NumPy | Cheap, it is already an object array | Creates a new array of Python objects |
The rows on memory, speed, and regex engine need explaining, so each gets a section below.
Default backend and how to change it
The default is set by the option mode.string_storage. In pandas 2.x it is "python". Pandas 3 changes the default so that it uses pyarrow when the package is installed. The next chapters cover that change. The option affects what dtype="string" means, and an explicit pd.StringDtype("python") or "string[pyarrow]" ignores it.
import pandas as pd
with pd.option_context("mode.string_storage", "pyarrow"):
s = pd.Series(["a", "b", None], dtype="string")
print(s.dtype)
t = pd.Series(["a", "b", None], dtype="string[python]")
print(t.dtype)Use option_context when you want a temporary choice. Setting pd.options.mode.string_storage at the top of a script changes every later use of dtype="string" in that process, including inside libraries you import. That makes it hard to trace problems, so prefer explicit dtypes in shared code.
To switch an existing column, call astype with the target dtype. The data is copied into the new layout.
import pandas as pd
s = pd.Series(["x", "y", None], dtype="string[python]")
converted = s.astype(pd.StringDtype("pyarrow"))
print(converted.dtype.storage)
print(converted.tolist())Memory
With python storage, every string is a full Python object, and the array holds a pointer to each one. A three-character string takes roughly 50 bytes, and the pointer adds 8 more. With pyarrow storage, the same string takes its three bytes plus a small offset entry. For columns of short strings the Arrow layout is often several times smaller.
You can measure this with memory_usage(deep=True).
import pandas as pd
values = ["red", "green", "blue"] * 1000
py = pd.Series(values, dtype=pd.StringDtype("python"))
pa = pd.Series(values, dtype=pd.StringDtype("pyarrow"))
print("python :", py.memory_usage(deep=True))
print("pyarrow:", pa.memory_usage(deep=True))Two cautions apply when you read these numbers.
- For
pythonstorage,deep=Trueadds up the size of every element, even when elements are the same object. The list above holds only three distinctstrobjects, repeated 1000 times each, so the real footprint is smaller than the reported one. Data read from a file usually has a separate object per row, so the report is closer to reality there. - The number measures the column, not the peak memory of building it. Reading a file into
pyarrowstorage can still use extra memory temporarily.
The memory gap grows with the number of rows and shrinks as strings get longer. For long text such as paragraphs, the character data dominates and the per-object overhead matters less.
Speed
Arrow can run many .str operations over the whole buffer in compiled code, without creating a Python object for each element. Operations such as upper, lower, len, startswith, and contains with a literal pattern benefit most. With python storage, pandas loops over the elements in Python, calling the str method on each one.
A rough benchmark on your own data is the only reliable way to know the gain.
import time
import pandas as pd
values = ["alpha beta", "gamma delta", None, "epsilon"] * 250_000
for storage in ["python", "pyarrow"]:
s = pd.Series(values, dtype=pd.StringDtype(storage))
start = time.perf_counter()
s.str.upper()
s.str.contains("ta", regex=False)
elapsed = time.perf_counter() - start
print(storage, round(elapsed, 3), "seconds")Expect pyarrow to win on this test. Do not expect the same ratio for every method. Some .str operations have no Arrow kernel and fall back to a Python loop, and the fallback includes the cost of converting the data. Operations that pass flags or use Python-specific features are the most likely to take this path.
Regex differences
When pandas runs a regular expression in Arrow, the engine is Google's RE2, not Python's re. RE2 is fast and safe against pathological patterns, but it does not support lookahead, lookbehind, or backreferences. A pattern that works with python storage can fail with pyarrow storage.
import pandas as pd
for storage in ["python", "pyarrow"]:
s = pd.Series(["abc", "xyz"], dtype=pd.StringDtype(storage))
try:
print(storage, s.str.contains(r"a(?=b)").tolist())
except Exception as exc:
print(storage, "failed:", type(exc).__name__)The python line prints [True, False]. On pyarrow storage, the lookahead is rejected with an error raised by Arrow. If you need these features, you have three options: rewrite the pattern without them, use python storage for that column, or avoid the pattern with literal checks (regex=False) when you can.
Mutation and conversion costs
Arrow arrays are immutable. Assigning to a single element, such as s.iloc[0] = "new" in a loop, makes pandas build a new array each time. Loops like this are slow with pyarrow storage and cheap with python storage. Prefer vectorized assignments such as s.where(...), s.mask(...), or .str.replace.
Converting to NumPy with to_numpy() or passing the column to a library that expects object arrays makes the pyarrow backend create Python string objects for every element. If your pipeline repeatedly moves text between pandas and such libraries, you may lose the memory advantage.
Not the same as ArrowDtype
pd.StringDtype("pyarrow") and pd.ArrowDtype(pa.string()) both use Arrow memory, but they are different dtypes. StringDtype follows the string contract above and works with the rest of the pandas string tooling. ArrowDtype is the general Arrow-backed dtype family. It has a wider range of types, and some of its behavior differs. For text columns in this tutorial, use StringDtype.
Decision guide
In short:
- Without
pyarrow, the choice is made for you. - If your code depends on Python
refeatures or per-element mutation, keeppythonstorage for those columns. - If a column is large, mostly read-only, and processed with common
.strmethods,pyarrowstorage usually saves memory and time. - For small data, the difference is not worth the extra dependency. Keep the default.
- If the column holds a few distinct values repeated many times, compare against
category, which a later chapter covers.
Checking what you have
Use these checks when you inherit a DataFrame and want to know which storage it uses.
import pandas as pd
df = pd.DataFrame({"name": ["Ada", "Alan", None]}, dtype="string")
print(df["name"].dtype)
print(df["name"].dtype.storage)
print(df["name"].array.__class__.__name__)The storage attribute tells you the backend. The array class name also differs between backends, which helps when debugging.
Exercise
A column of 5 million short product codes is read-only after loading and is filtered with .str.startswith and .str.contains("-", regex=False). A teammate proposes switching it to pd.StringDtype("pyarrow"). Name two benefits you expect and one thing to verify before committing to the change.
Show answer
Expected benefits: lower memory, because Arrow stores the bytes in one buffer instead of 5 million Python objects, and faster startswith and literal contains, because both have Arrow kernels. Verify that pyarrow is installed in every environment that runs the code, and measure memory and timing on a sample, since the gain depends on the data. Also check that no other code in the pipeline relies on Python re features or assigns elements one at a time.
Exercise
This code works on string[python] but fails after the column is converted to string[pyarrow]: s.str.contains(r"(\w)\1"). Why does it fail, and how can you keep the logic?
Show answer
The pattern uses a backreference (\1) to find a repeated character. Arrow evaluates regular expressions with RE2, which does not support backreferences, so it raises an error. To keep the logic, convert that column back to string[python] with astype(pd.StringDtype("python")) before the check, or rewrite the check without a backreference.