Skip to content

BUG: construct_1d_ndarray_preserving_na with dt64/td64 and object dtype #40068

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 3 commits into from
Feb 26, 2021
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
11 changes: 10 additions & 1 deletion pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1829,7 +1829,16 @@ def construct_1d_ndarray_preserving_na(
else:
if dtype is not None:
_disallow_mismatched_datetimelike(values, dtype)
subarr = np.array(values, dtype=dtype, copy=copy)

if (
dtype == object
and isinstance(values, np.ndarray)
and values.dtype.kind in ["m", "M"]
):
# TODO(numpy#12550): special-case can be removed
subarr = construct_1d_object_array_from_listlike(list(values))
else:
subarr = np.array(values, dtype=dtype, copy=copy)

return subarr

Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/dtypes/cast/test_construct_ndarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,13 @@
def test_construct_1d_ndarray_preserving_na(values, dtype, expected):
result = construct_1d_ndarray_preserving_na(values, dtype=dtype)
tm.assert_numpy_array_equal(result, expected)


@pytest.mark.parametrize("dtype", ["m8[ns]", "M8[ns]"])
def test_construct_1d_ndarray_preserving_na_datetimelike(dtype):
arr = np.arange(5, dtype=np.int64).view(dtype)
expected = np.array(list(arr), dtype=object)
assert all(isinstance(x, type(arr[0])) for x in expected)

result = construct_1d_ndarray_preserving_na(arr, np.dtype(object))
tm.assert_numpy_array_equal(result, expected)