Skip to content

BUG: Fix export .to_numpy() with nullable type #41196

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

Closed
wants to merge 2 commits into from
Closed
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,7 @@ Conversion
- Bug in :func:`factorize` where, when given an array with a numeric numpy dtype lower than int64, uint64 and float64, the unique values did not keep their original dtype (:issue:`41132`)
- Bug in :class:`DataFrame` construction with a dictionary containing an arraylike with ``ExtensionDtype`` and ``copy=True`` failing to make a copy (:issue:`38939`)
- Bug in :meth:`qcut` raising error when taking ``Float64DType`` as input (:issue:`40730`)
- Bug in :meth:`BaseMaskedArray.to_numpy` does not output ``numeric_dtype`` with ``numeric_dtype`` input (:issue:`40630`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find this sentence a bit difficult to understand, can you rephrase please?


Strings
^^^^^^^
Expand Down
34 changes: 29 additions & 5 deletions pandas/core/arrays/masked.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
from pandas.core.dtypes.common import (
is_dtype_equal,
is_integer,
is_integer_dtype,
is_numeric_dtype,
is_object_dtype,
is_scalar,
is_string_dtype,
Expand Down Expand Up @@ -244,7 +246,12 @@ def to_numpy( # type: ignore[override]

Examples
--------
An object-dtype is the default result
Other than numerical type input (int and float), object-dtype is
the default result

>>> a = pd.Series([1, 2, 3], dtype=pd.Int64Dtype())
>>> a.to_numpy()
array([1, 2, 3], dtype=int64)

>>> a = pd.array([True, False, pd.NA], dtype="boolean")
>>> a.to_numpy()
Expand Down Expand Up @@ -280,10 +287,27 @@ def to_numpy( # type: ignore[override]
if na_value is lib.no_default:
na_value = libmissing.NA
if dtype is None:
# error: Incompatible types in assignment (expression has type
# "Type[object]", variable has type "Union[str, dtype[Any], None]")
dtype = object # type: ignore[assignment]
if self._hasna:
if is_numeric_dtype(self):
dtype = self.dtype.numpy_dtype
else:
# error: Incompatible types in assignment (expression has type
# "Type[object]", variable has type "Union[str, dtype[Any], None]")
dtype = object # type: ignore[assignment]

if is_numeric_dtype(self):

# If there is NA and the data is of int type, a float
# is being returned as int type cannot support np.nan.
if is_integer_dtype(self) and self._hasna:
data = self._data.astype(float)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't this ignore any specified dtype?

else:
data = self._data.astype(dtype)

# For numerical input, pd.na is replaced with np.nan
if self._hasna is True:
data[np.where(self._mask is True)] = np.nan
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line looks suspect ... self._mask is an ndarray, so won't comparing identity with True just always give False?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, what about the specified na_value?


elif self._hasna:
if (
not is_object_dtype(dtype)
and not is_string_dtype(dtype)
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/arrays/test_numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,21 @@ def test_to_numpy():
tm.assert_numpy_array_equal(result, expected)


@pytest.mark.parametrize(
"data_content,data_type,expected_result",
[
([1, 2, 3], pd.Float64Dtype(), np.array([1, 2, 3], dtype=np.float64)),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not build the Series here instead? I think just two parameters data and expected_results is enough (I think expected is descriptive enough and more common, but no big deal).

([1, 2, 3], "Int64", np.array([1, 2, 3], dtype=np.int64)),
([1, 2, pd.NA], pd.Float64Dtype(), np.array([1, 2, np.nan], dtype=np.float64)),
([1, 2, pd.NA], "Int64", np.array([1, 2, np.nan], dtype=np.float64)),
],
)
def test_to_numpy_int_float(data_content, data_type, expected_result):
data = pd.Series(data_content, dtype=data_type)
actual_result = data.to_numpy()
assert np.array_equal(actual_result, expected_result, equal_nan=True)


# ----------------------------------------------------------------------------
# Setitem

Expand Down