Skip to content

BUG: to_numpy for PandasArray does not handle na_value #50331

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -931,7 +931,7 @@ ExtensionArray
- Bug in :meth:`Series.mean` overflowing unnecessarily with nullable integers (:issue:`48378`)
- Bug in :meth:`Series.tolist` for nullable dtypes returning numpy scalars instead of python scalars (:issue:`49890`)
- Bug when concatenating an empty DataFrame with an ExtensionDtype to another DataFrame with the same ExtensionDtype, the resulting dtype turned into object (:issue:`48510`)
-
- Bug in :meth:`array.PandasArray.to_numpy` raising with ``NA`` value when ``na_value`` is specified (:issue:`40638`)

Styler
^^^^^^
Expand Down
14 changes: 9 additions & 5 deletions pandas/core/arrays/numpy_.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,13 +389,17 @@ def to_numpy(
copy: bool = False,
na_value: object = lib.no_default,
) -> np.ndarray:
result = np.asarray(self._ndarray, dtype=dtype)
mask = self.isna()
if na_value is not lib.no_default and mask.any():
result = self._ndarray.copy()
result[mask] = na_value
else:
result = self._ndarray

if (copy or na_value is not lib.no_default) and result is self._ndarray:
result = result.copy()
result = np.asarray(result, dtype=dtype)

if na_value is not lib.no_default:
result[self.isna()] = na_value
if copy and result is self._ndarray:
result = result.copy()

return result

Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/arrays/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,3 +413,11 @@ def test_array_not_registered(registry_without_decimal):
result = pd.array(data, dtype=DecimalDtype)
expected = DecimalArray._from_sequence(data)
tm.assert_equal(result, expected)


def test_array_to_numpy_na():
# GH#40638
arr = pd.array([pd.NA, 1], dtype="string")
result = arr.to_numpy(na_value=True, dtype=bool)
expected = np.array([True, True])
tm.assert_numpy_array_equal(result, expected)