Skip to content

Commit ccd6c00

Browse files
author
MarcoGorelli
committed
BUG: 'Series.to_numpy(dtype=, na_value=)' behaves differently with 'pd.NA' and 'np.nan'
1 parent c0c6537 commit ccd6c00

File tree

3 files changed

+7
-3
lines changed

3 files changed

+7
-3
lines changed

doc/source/whatsnew/v1.6.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@ Indexing
216216
Missing
217217
^^^^^^^
218218
- Bug in :meth:`Index.equals` raising ``TypeError`` when :class:`Index` consists of tuples that contain ``NA`` (:issue:`48446`)
219+
- Bug when calling :meth:`Series.to_numpy` on a Series of ``object`` dtype containing ``pd.NA`` was raising even if ``na_value`` was valid (:issue:`48951`)
219220
-
220221

221222
MultiIndex

pandas/core/base.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -537,12 +537,14 @@ def to_numpy(
537537
f"to_numpy() got an unexpected keyword argument '{bad_keys}'"
538538
)
539539

540-
result = np.asarray(self._values, dtype=dtype)
541540
# TODO(GH-24345): Avoid potential double copy
542541
if copy or na_value is not lib.no_default:
543-
result = result.copy()
542+
result = self._values.copy()
544543
if na_value is not lib.no_default:
545544
result[np.asanyarray(self.isna())] = na_value
545+
result = np.asarray(result, dtype=dtype)
546+
else:
547+
result = np.asarray(self._values, dtype=dtype)
546548
return result
547549

548550
@property

pandas/tests/base/test_conversion.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,7 @@ def test_to_numpy_dtype(as_series):
398398
"values, dtype, na_value, expected",
399399
[
400400
([1, 2, None], "float64", 0, [1.0, 2.0, 0.0]),
401+
([1, 2, pd.NA, 4], "int32", 0, [1, 2, 0, 4]),
401402
(
402403
[Timestamp("2000"), Timestamp("2000"), pd.NaT],
403404
None,
@@ -411,7 +412,7 @@ def test_to_numpy_na_value_numpy_dtype(
411412
):
412413
obj = index_or_series(values)
413414
result = obj.to_numpy(dtype=dtype, na_value=na_value)
414-
expected = np.array(expected)
415+
expected = np.array(expected, dtype=dtype)
415416
tm.assert_numpy_array_equal(result, expected)
416417

417418

0 commit comments

Comments
 (0)