You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In NumPy 2.0>, the stricter semantics for the copy=False keyword result in a ValueError in np.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.
ValueError: Unable to avoid copy while 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 change in 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 but copy=False was passed.
Proposed Fix
Instead of forcing the user to pre-convert input using np.asarray(data) before passing it to nan_to_num, the function should handle this gracefully by adapting its internal logic.
This preserves the original intent (copy if needed) and avoids unnecessary burden on users to refactor existing code.
Additional Context
The migration guide recommends replacing np.array(..., copy=False) with np.asarray(...) when the goal is "copy if needed". This change would make nan_to_num robust across versions and eliminate the need for callers to pre-process data explicitly.
changed the title [-]BUG: `np.nan_to_num(..., copy=False)` raises `ValueError` in NumPy 2.0 when array creation requires copy[/-][+]DOC: `np.nan_to_num(..., copy=)` uses NumPy 1.x description[/+]on May 25, 2025
You should just use copy=None and the documentation should be changed. It's best to keep the meaning of copy= aligned with the rest of NumPy even if copy=None is a bit awkward, I would say.
So this is just a doc change, because the docs read a bit like copy was different here.
Activity
[-]BUG: `np.nan_to_num(..., copy=False)` raises `ValueError` in NumPy 2.0 when array creation requires copy[/-][+]DOC: `np.nan_to_num(..., copy=)` uses NumPy 1.x description[/+]seberg commentedon May 25, 2025
You should just use
copy=Noneand the documentation should be changed. It's best to keep the meaning ofcopy=aligned with the rest of NumPy even ifcopy=Noneis a bit awkward, I would say.So this is just a doc change, because the docs read a bit like
copywas different here.akshitasure12 commentedon May 28, 2025
I'm a new contributor to NumPy and came across this issue - Hope it still needs to be addressed!
Fix doc for nan_to_num
DOC: Clarify copy parameter semantics in nan_to_num (gh-29045)
Merge pull request #32575 from Rvish-glitch/fix-nan-to-num-copy-docs