Sub topic 6
Read-only arrays from to_numpy() and .values
This chapter assumes you know how to select columns with df["a"], that NumPy arrays are mutable, and that the previous chapters' rule holds: a derived object never changes the object it came from.
Why arrays are a special case
Most pandas methods return a new DataFrame or Series. Under Copy-on-Write (CoW), that object behaves as an independent copy, and pandas defers the real copy until a write happens.
to_numpy() and .values are different because they return a NumPy array, not a pandas object. NumPy knows nothing about CoW. If pandas handed out a writeable array that shares memory with the DataFrame, writing to the array would silently change the DataFrame. That would break the CoW rule.
pandas 3 avoids this by marking the array read-only. A read-only array is one whose writeable flag is False, so NumPy refuses any in-place write to it.
Seeing the flag
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
arr = df["a"].to_numpy()
print(arr.flags.writeable) # FalseThe same applies to .values, and to np.asarray(df["a"]), which goes through the same machinery. Reading is unaffected:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
arr = df["a"].to_numpy()
print(arr.sum()) # 6
print(arr[1:]) # [2 3]
print(arr * 2) # [2 4 6], this builds a new array, so it is allowedOperations that create a new array, such as arr * 2, are fine. Only in-place writes fail.
The error you will see
Code written for pandas 2.x often modifies the array in place. In pandas 3 that raises an error:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
arr = df["a"].to_numpy()
try:
arr[0] = 100
except ValueError as err:
print(err) # assignment destination is read-only
print(df["a"].iloc[0]) # 1, df was never touchedThe message comes from NumPy, not pandas. The error is deliberate. In pandas 2.x the same line sometimes changed df and sometimes did not, depending on dtype and internal layout. Now it fails every time, so you find the problem immediately.
Common places this shows up:
- In-place NumPy functions, such as
np.clip(arr, 0, 10, out=arr)orarr.sort(). - Numerical or machine-learning code that normalizes its input array in place.
- Helper functions that accept
df.valuesand modify it for speed.
Fixing it: take an explicit copy
If you want to modify the data without affecting the DataFrame, copy first:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
arr = df["a"].to_numpy().copy()
arr[0] = 100 # allowed
print(arr) # [100 2 3]
print(df["a"].iloc[0]) # 1, df is not affecteddf["a"].to_numpy(copy=True) does the same in one call. Either way, the copy is deliberate and visible in the code.
If you want the DataFrame to change, do not write through the array. Assign back with .loc or .iloc, as in the earlier chapter on assignment:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
arr = df["a"].to_numpy().copy()
arr[0] = 100
df["a"] = arr # replace the column with the modified data
print(df["a"].tolist()) # [100, 2, 3]When the array is not a view
Not every call returns a view of existing memory. A DataFrame with mixed column types (for example integers and strings) has no single block of memory to expose, so df.to_numpy() must build a new array. Do not rely on that detail. Treat every array from to_numpy() or .values as read-only and copy before writing. Code that follows this rule behaves the same for every dtype.
Quick reference
| You write | Result under pandas 3 |
|---|---|
| `arr = s.to_numpy()` then `arr[0] = 1` | `ValueError`, read-only |
| `arr = s.to_numpy().copy()` then `arr[0] = 1` | Works, `s` unchanged |
| `arr = s.to_numpy(copy=True)` then `arr[0] = 1` | Works, `s` unchanged |
| `s.iloc[0] = 1` | Works, updates `s` |
| `arr.sum()`, `arr[1:]`, `arr * 2` | Works, nothing is modified in place |
Exercise
Exercise
A function receives a DataFrame and runs x = df["score"].values; x[x < 0] = 0 to clip negative scores. After upgrading to pandas 3 it raises "assignment destination is read-only". Give two fixes: one that leaves df unchanged and one that updates df.
Show answer
To leave df unchanged, copy first: x = df["score"].to_numpy().copy(); x[x < 0] = 0. To update df, assign through pandas in one step: df.loc[df["score"] < 0, "score"] = 0. A copy followed by df["score"] = x also works.