Skip to content

Lose the index before 'na_value' assignment in 'to_numpy' #45775

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 14 commits into from
Mar 5, 2022
Merged
Show file tree
Hide file tree
Changes from 10 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
3 changes: 1 addition & 2 deletions doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -348,8 +348,7 @@ Missing

MultiIndex
^^^^^^^^^^
-
-
- Bug in :meth:`Series.to_numpy` where multiindexed Series could not be converted to numpy arrays when an ``na_value`` was supplied (:issue:`45774`)

I/O
^^^
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,9 @@ def to_numpy(
if copy or na_value is not lib.no_default:
result = result.copy()
if na_value is not lib.no_default:
result[self.isna()] = na_value
# Convert the mask to numpy in order to prevent possible
# issues with multiindex compatibility (#45774)
result[np.asanyarray(self.isna())] = na_value
return result

@property
Expand Down
36 changes: 36 additions & 0 deletions pandas/tests/base/test_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,42 @@ def test_to_numpy_na_value_numpy_dtype(
tm.assert_numpy_array_equal(result, expected)


@pytest.mark.parametrize(
"data, multiindex, dtype, na_value, expected",
[
(
[1, 2, None, 4],
[(0, "a"), (0, "b"), (1, "b"), (1, "c")],
float,
np.nan,
[1.0, 2.0, np.nan, 4.0],
),
(
[1.0, 2.0, np.nan, 4.0],
[("a", 0), ("a", 1), ("a", 2), ("b", 0)],
int,
0,
[1, 2, 0, 4],
),
(
[Timestamp("2000"), Timestamp("2000"), pd.NaT],
[(0, Timestamp("2021")), (0, Timestamp("2022")), (1, Timestamp("2000"))],
None,
Timestamp("2000"),
[np.datetime64("2000-01-01T00:00:00.000000000")] * 3,
),
],
)
def test_to_numpy_multiindex_series_na_value(
data, multiindex, dtype, na_value, expected
):
index = pd.MultiIndex.from_tuples(multiindex)
series = Series(data, index=index)
result = series.to_numpy(dtype=dtype, na_value=na_value)
expected = np.array(expected)
tm.assert_numpy_array_equal(result, expected)


def test_to_numpy_kwargs_raises():
# numpy
s = Series([1, 2, 3])
Expand Down