Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork10.9k
Description
Describe the issue:
In NumPy 2.0>, the stricter semantics for thecopy=False
keyword result in aValueError
innp.nan_to_num
when the input is not already a NumPy array or when a copy is required due to dtype mismatch.
This breaks previously valid and widely used patterns that worked in NumPy 1.x.
Reproduce the code example:
importnumpyasnpdata= [float("nan"),float("inf"),1.0]np.nan_to_num(data,copy=False)# raises ValueError in NumPy 2.0
Error message:
ValueError: Unable to avoid copywhile creating an array as requested.If using`np.array(obj, copy=False)` replace it with`np.asarray(obj)` to allow a copy when needed (no behavior changein NumPy 1.x).
Python and NumPy Versions:
- NumPy version: 2.0.x
- Python version: 3.10+
- OS: Any
Runtime Environment:
No response
Context for the issue:
Cause
Internally,nan_to_num
uses:
x=np.array(x,subok=True,copy=copy)
In NumPy 2.0, this raises an error if a copy is needed butcopy=False
was passed.
Proposed Fix
Instead of forcing the user to pre-convert input usingnp.asarray(data)
before passing it tonan_to_num
, the function should handle this gracefully by adapting its internal logic.
Proposed replacement:
ifcopyisFalse:x=np.asarray(x)else:x=np.array(x,subok=True,copy=copy)
This preserves the original intent (copy if needed
) and avoids unnecessary burden on users to refactor existing code.
Additional Context
Themigration guide recommends replacingnp.array(..., copy=False)
withnp.asarray(...)
when the goal is "copy if needed". This change would makenan_to_num
robust across versions and eliminate the need for callers to pre-process data explicitly.