Sub topic 6
Read-only arrays from to_numpy() and .values
This chapter covers what happens when you move data from pandas into NumPy under Copy-on-Write (CoW). It explains why the resulting array is often read-only, how to detect that, and how to write code that works either way.
Prerequisites
This chapter assumes you know:
- How to create DataFrames and Series and select columns and rows.
- The CoW rule from earlier chapters: an object derived from another pandas object never changes the original.
- Lazy copies: pandas shares memory between related objects and copies only on the first write.
- The basics of NumPy arrays, including indexing and in-place operators such as
+=.
Why the array is read-only
A pandas column is stored in a NumPy array. When you call to_numpy() on a numeric column, the cheapest result is a NumPy array that points at the same memory. This is a view, and it costs no copying.
That view creates a problem for the CoW rule. If you could write into the array, you would change the DataFrame that produced it. The array is a derived object, and derived objects must not change their source.
pandas 3 resolves this by marking such arrays as read-only. The array shares memory with the DataFrame, but NumPy refuses writes to it. Reads stay fast and the original stays protected.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
arr = df["a"].to_numpy()
print(arr.flags.writeable) # FalseThe flags.writeable attribute is NumPy's own switch. When it is False, any attempt to write into the array raises an error.
What the error looks like
Code written for pandas 2.x often modified these arrays without a second thought. In pandas 3, that code fails at the point of the write:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4.0, 5.0, 6.0]})
arr = df["a"].to_numpy()
try:
arr[0] = 100
except ValueError as err:
print(err) # assignment destination is read-only
try:
arr += 1
except ValueError as err:
print(err) # output array is read-only
print(df["a"].tolist()) # [1, 2, 3]Both failures are ValueError, but the messages differ.
- Item assignment such as
arr[0] = 100says the assignment destination is read-only. - In-place operators such as
+=and ufuncs called without=arrsay the output array is read-only.
The failure is loud on purpose. In pandas 2.x the same write would silently succeed. Whether it also changed the DataFrame depended on internal storage details that you could not see. That is the view-or-copy ambiguity from the first chapter, now turned into a clear error.
Which calls return read-only arrays
All of the following accessors can return an array that shares memory with pandas data:
Series.to_numpy()andDataFrame.to_numpy()Series.valuesandDataFrame.valuesnp.asarray(series)andnp.asarray(df), which ask pandas for its array without requesting a copy
| Expression | Result under CoW |
|---|---|
| `series.to_numpy()` on a NumPy-backed column | Read-only view of the column data |
| `series.values` | Read-only view, same as above |
| `df.to_numpy()` where all columns share one dtype | Read-only view of the block of data |
| `df.to_numpy()` where columns have mixed dtypes | pandas builds a new array. Check `flags.writeable` instead of assuming |
| `series.to_numpy(copy=True)` | Independent copy, writeable |
| `np.array(series)` | Copy by default, writeable |
Two points about the table.
First, whether pandas can return a view depends on how the data is stored. A single-dtype DataFrame can hand out its internal block directly. A DataFrame with, say, integer and float columns has to build a new combined array. A column using a non-NumPy dtype, such as the default string dtype, also has to be converted into a new array. Those results are fresh objects, but you should not build logic around which case you are in. A later pandas version may change what is shared. Check the flag when it matters, or request a copy explicitly.
Second, to_numpy(dtype=...) may or may not copy, depending on whether the dtype conversion is needed. The writeable flag is not a reliable signal for "this is a copy". Use copy=True when you need to write.
Making a writeable array
If you must modify the values, take an explicit copy. There are two common ways:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
# Option 1: ask pandas for a copy up front.
values = df["a"].to_numpy(copy=True)
values[0] = 100
values += 1
print(values) # [101 3 4]
print(df["a"].tolist()) # [1, 2, 3]
# Option 2: copy the read-only view.
values = df["a"].to_numpy().copy()
values[0] = 100
print(df["a"].iloc[0]) # 1Option 1 is usually better. With a plain to_numpy() followed by .copy(), you ask for a view and then immediately copy it, which is no cheaper than asking for the copy directly. For data that pandas must convert anyway, copy=True can also avoid a second copy.
A third option avoids the question entirely. Arithmetic on a read-only array does not modify it. It builds a new array, and that new array is writeable:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
shifted = df["a"].to_numpy() + 1
print(shifted.flags.writeable) # True
shifted[0] = 0
print(df["a"].tolist()) # [1, 2, 3]Here the + 1 creates a new array, so you pay for exactly one copy, and you were going to compute the new values anyway.
Choosing between copying and not mutating
Read-only arrays push you toward a cleaner style. Before reaching for copy=True, ask whether you need to mutate the array at all.
- If you only read the values, for example to pass them to a plotting function or compute a statistic, do nothing. The read-only view is the fastest option and needs no copy.
- If you compute new values from the old ones, use an expression that returns a new array, such as
arr * 2,np.clip(arr, 0, 1), ornp.where(arr > 0, arr, 0). These do not need a copy beforehand. - If you must change values in place, for example to feed a routine that works destructively on its input, call
to_numpy(copy=True)once and work on that.
The following example fits case 3. It standardizes numeric columns and returns a new array. The input frame is untouched.
import numpy as np
import pandas as pd
def standardize(frame: pd.DataFrame) -> np.ndarray:
data = frame.to_numpy(dtype="float64", copy=True)
data -= data.mean(axis=0)
data /= data.std(axis=0)
return data
frame = pd.DataFrame({"x": [1, 2, 3], "y": [10, 20, 40]})
result = standardize(frame)
print(result.round(2))
print(frame["x"].tolist()) # [1, 2, 3], the frame is unchangedThe explicit copy=True is what makes the -= and /= lines legal. It also documents your intent for the next reader, who would otherwise wonder why the code copies.
Getting results back into pandas
After you finish with a writeable array, assign the result back through a normal pandas assignment. Do not try to write through the array.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
values = df["a"].to_numpy(copy=True)
values[values > 1] = 0
df["a"] = values
print(df["a"].tolist()) # [1, 0, 0]The assignment is what updates df. Treat the array as scratch space. Once you have assigned it, stop modifying it, because you no longer know how pandas stores it.
Where the error shows up in practice
You will rarely write arr[0] = 100 against a pandas array on purpose. The error more often comes from deeper in a call stack.
- Libraries that work in place. Some numerical routines write into their input. The error then comes from inside the library, and the traceback points at library code, not yours. Pass them a copy.
- Numba and similar compilers. Compiled functions that take an array argument and write to it fail with a read-only message, or in some cases a typing error. Call them with
to_numpy(copy=True). - Out parameters.
np.add(a, b, out=df["a"].to_numpy())fails, becauseoutmust be writeable. Allocate your own output withnp.empty_like(...). - Old helper functions. Utility functions written for pandas 2.x often do
x = df.values; x[mask] = 0and rely on the side effect of changing the frame. That side effect was never guaranteed. Under pandas 3 it becomes an error, and the fix is a.locassignment, as the chapter on assignment showed.
The last case deserves attention, because sometimes the old code was a bug that happened to work. If a function silently updated a DataFrame through its values, the new error is pointing at a hidden dependency. Rewrite it to assign explicitly:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
# Old pattern, which fails in pandas 3:
# x = df.values
# x[x > 4] = 0
# Explicit replacement that works in pandas 3:
df = df.mask(df > 4, 0)
print(df)Gotchas
Do not flip the flag
NumPy lets you run arr.flags.writeable = True on some arrays. For a view of pandas data, this removes the protection and can modify the original DataFrame, which breaks the CoW rule. pandas may also have other objects sharing the same memory, and they will all see the change. If you need to write, copy instead.
The array is not a snapshot
A read-only view points at the live data. pandas cannot track NumPy arrays that you hold, so if you later modify the DataFrame in place, for example with df.loc[0, "a"] = 100, an array you took earlier may show the new value. Treat the view as valid for immediate use. If you need values frozen at a point in time, take a copy at that point.
Read-only does not mean immutable data
The flag protects the array. It does not make the DataFrame immutable. You can still change the DataFrame through pandas methods, and those changes follow the CoW rules from earlier chapters.
Check the flag instead of the method
If you are writing a function that accepts arrays from many sources, do not assume anything about the caller. Some arrays arrive writeable, others read-only. A defensive pattern is:
import numpy as np
def ensure_writeable(arr: np.ndarray) -> np.ndarray:
return arr if arr.flags.writeable else arr.copy()This copies only when needed. Remember, though, that a writeable array may still be shared with something else, so only use it when mutating the caller's data would be harmless.
A decision guide
The diagram summarizes the choice you face whenever you hold an array from pandas.
Summary of behavior
- Under CoW, an array that shares memory with a DataFrame or Series is read-only, so writing to it cannot change the original.
to_numpy(),.values, andnp.asarray()can all return such arrays.- Writing to one raises
ValueError, and the message names a read-only destination or output array. - Use
to_numpy(copy=True)when you need to modify values in place. - Prefer expressions that return new arrays, then assign the result back to pandas.
- Do not set
flags.writeable = Trueon a view of pandas data. - Do not rely on a view as a snapshot, and do not rely on the flag to tell you whether pandas copied.
Exercise
The following code worked in pandas 2.x and now fails in pandas 3. Explain why, then rewrite it in two ways: one that keeps the DataFrame unchanged, and one that updates the DataFrame. import pandas as pd df = pd.DataFrame({"score": [10, 20, 30]}) scores = df["score"].to_numpy() scores[scores > 15] = 15
Show answer
In pandas 3, tonumpy() on a NumPy-backed column returns a read-only view that shares memory with the DataFrame. The write scores[scores > 15] = 15 raises ValueError (assignment destination is read-only), because allowing it would change the DataFrame through a derived object. Version that leaves df unchanged: scores = df["score"].tonumpy(copy=True) scores[scores > 15] = 15 Version that updates df, using a single .loc assignment: df.loc[df["score"] > 15, "score"] = 15 Either option also works by building a new array and assigning it back: df["score"] = df["score"].clip(upper=15).
Exercise
A teammate says: "To avoid the read-only error, I run arr.flags.writeable = True right after calling df.to_numpy(). It is faster than copying." Give two reasons this is a bad idea.
Show answer
First, the array is a view of memory that the DataFrame owns, so writing to it can change the DataFrame, which breaks the CoW rule that derived objects never modify their source. Second, pandas may be sharing that memory with other objects, such as other DataFrames derived from this one, and they would change too, with no warning. The speed gain is also not guaranteed to matter, and to_numpy(copy=True) costs one copy for code that is correct. If you need to write, copy.
Exercise
You call np.asarray(df) on a DataFrame with one integer column and one float column. Your colleague asserts that the result is certainly a copy and therefore writeable. How should you handle this in code that must work across pandas versions?
Show answer
Do not rely on the assertion. With mixed dtypes pandas builds a combined array, so it is likely a new object, but whether it is writeable or shared can depend on the pandas version and the dtypes involved. If the code writes to the array, request the copy explicitly with df.to_numpy(copy=True), or check arr.flags.writeable and copy only when it is False.