Skip to content

Commit 6efc5af

Browse files
authored
BUG: construct_1d_ndarray_preserving_na with dt64/td64 and object dtype (#40068)
1 parent 44adb8f commit 6efc5af

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

pandas/core/dtypes/cast.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -1829,7 +1829,16 @@ def construct_1d_ndarray_preserving_na(
18291829
else:
18301830
if dtype is not None:
18311831
_disallow_mismatched_datetimelike(values, dtype)
1832-
subarr = np.array(values, dtype=dtype, copy=copy)
1832+
1833+
if (
1834+
dtype == object
1835+
and isinstance(values, np.ndarray)
1836+
and values.dtype.kind in ["m", "M"]
1837+
):
1838+
# TODO(numpy#12550): special-case can be removed
1839+
subarr = construct_1d_object_array_from_listlike(list(values))
1840+
else:
1841+
subarr = np.array(values, dtype=dtype, copy=copy)
18331842

18341843
return subarr
18351844

pandas/tests/dtypes/cast/test_construct_ndarray.py

+10
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,13 @@
1919
def test_construct_1d_ndarray_preserving_na(values, dtype, expected):
2020
result = construct_1d_ndarray_preserving_na(values, dtype=dtype)
2121
tm.assert_numpy_array_equal(result, expected)
22+
23+
24+
@pytest.mark.parametrize("dtype", ["m8[ns]", "M8[ns]"])
25+
def test_construct_1d_ndarray_preserving_na_datetimelike(dtype):
26+
arr = np.arange(5, dtype=np.int64).view(dtype)
27+
expected = np.array(list(arr), dtype=object)
28+
assert all(isinstance(x, type(arr[0])) for x in expected)
29+
30+
result = construct_1d_ndarray_preserving_na(arr, np.dtype(object))
31+
tm.assert_numpy_array_equal(result, expected)

0 commit comments

Comments
 (0)