Skip to content

Commit ec48bd4

Browse files
authored
REGR: Fix regression in to_numpy (#50606)
* Use array equal fast * Revert * Add test
1 parent 89a018e commit ec48bd4

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

pandas/core/base.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
doc,
3939
)
4040

41+
from pandas.core.dtypes.cast import can_hold_element
4142
from pandas.core.dtypes.common import (
4243
is_categorical_dtype,
4344
is_dict_like,
@@ -532,7 +533,15 @@ def to_numpy(
532533
)
533534

534535
if na_value is not lib.no_default:
535-
values = self._values.copy()
536+
values = self._values
537+
if not can_hold_element(values, na_value):
538+
# if we can't hold the na_value asarray either makes a copy or we
539+
# error before modifying values. The asarray later on thus won't make
540+
# another copy
541+
values = np.asarray(values, dtype=dtype)
542+
else:
543+
values = values.copy()
544+
536545
values[np.asanyarray(self.isna())] = na_value
537546
else:
538547
values = self._values

pandas/tests/series/methods/test_to_numpy.py

+8
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,11 @@ def test_to_numpy_na_value(dtype):
1515
result = ser.to_numpy(dtype=dtype, na_value=0)
1616
expected = np.array([1, 2, 0, 4], dtype=dtype)
1717
tm.assert_numpy_array_equal(result, expected)
18+
19+
20+
def test_to_numpy_cast_before_setting_na():
21+
# GH#50600
22+
ser = Series([1])
23+
result = ser.to_numpy(dtype=np.float64, na_value=np.nan)
24+
expected = np.array([1.0])
25+
tm.assert_numpy_array_equal(result, expected)

0 commit comments

Comments
 (0)