Skip to content

Commit ac762af

Browse files
authored
BUG: to_numpy for PandasArray does not handle na_value (#50331)
1 parent 44fc0fd commit ac762af

File tree

3 files changed

+18
-6
lines changed

3 files changed

+18
-6
lines changed

doc/source/whatsnew/v2.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -936,7 +936,7 @@ ExtensionArray
936936
- Bug in :meth:`Series.mean` overflowing unnecessarily with nullable integers (:issue:`48378`)
937937
- Bug in :meth:`Series.tolist` for nullable dtypes returning numpy scalars instead of python scalars (:issue:`49890`)
938938
- Bug when concatenating an empty DataFrame with an ExtensionDtype to another DataFrame with the same ExtensionDtype, the resulting dtype turned into object (:issue:`48510`)
939-
-
939+
- Bug in :meth:`array.PandasArray.to_numpy` raising with ``NA`` value when ``na_value`` is specified (:issue:`40638`)
940940

941941
Styler
942942
^^^^^^

pandas/core/arrays/numpy_.py

+9-5
Original file line numberDiff line numberDiff line change
@@ -389,13 +389,17 @@ def to_numpy(
389389
copy: bool = False,
390390
na_value: object = lib.no_default,
391391
) -> np.ndarray:
392-
result = np.asarray(self._ndarray, dtype=dtype)
392+
mask = self.isna()
393+
if na_value is not lib.no_default and mask.any():
394+
result = self._ndarray.copy()
395+
result[mask] = na_value
396+
else:
397+
result = self._ndarray
393398

394-
if (copy or na_value is not lib.no_default) and result is self._ndarray:
395-
result = result.copy()
399+
result = np.asarray(result, dtype=dtype)
396400

397-
if na_value is not lib.no_default:
398-
result[self.isna()] = na_value
401+
if copy and result is self._ndarray:
402+
result = result.copy()
399403

400404
return result
401405

pandas/tests/arrays/test_array.py

+8
Original file line numberDiff line numberDiff line change
@@ -413,3 +413,11 @@ def test_array_not_registered(registry_without_decimal):
413413
result = pd.array(data, dtype=DecimalDtype)
414414
expected = DecimalArray._from_sequence(data)
415415
tm.assert_equal(result, expected)
416+
417+
418+
def test_array_to_numpy_na():
419+
# GH#40638
420+
arr = pd.array([pd.NA, 1], dtype="string")
421+
result = arr.to_numpy(na_value=True, dtype=bool)
422+
expected = np.array([True, True])
423+
tm.assert_numpy_array_equal(result, expected)

0 commit comments

Comments
 (0)