diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 137be168985d2..0f246e58ed016 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -511,6 +511,7 @@ Metadata Other ^^^^^ +- Bug in :class:`DataFrame` and :class:`Series` raising for data of complex dtype when ``NaN`` values are present (:issue:`53627`) - Bug in :class:`FloatingArray.__contains__` with ``NaN`` item incorrectly returning ``False`` when ``NaN`` values are present (:issue:`52840`) - Bug in :func:`api.interchange.from_dataframe` when converting an empty DataFrame object (:issue:`53155`) - Bug in :func:`assert_almost_equal` now throwing assertion error for two unequal sets (:issue:`51727`) diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index f7934865fbb43..a622de742a840 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -2485,7 +2485,14 @@ def maybe_convert_objects(ndarray[object] objects, elif util.is_nan(val): seen.nan_ = True mask[i] = True - floats[i] = complexes[i] = val + if util.is_complex_object(val): + floats[i] = fnan + complexes[i] = val + seen.complex_ = True + if not convert_numeric: + break + else: + floats[i] = complexes[i] = val elif util.is_bool_object(val): seen.bool_ = True bools[i] = val diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 4bf16b6d20d1f..ceb283ca9e9e7 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -2154,3 +2154,18 @@ def test_index_ordered_dict_keys(): ), ) tm.assert_series_equal(series, expected) + + +@pytest.mark.parametrize( + "input_list", + [ + [1, complex("nan"), 2], + [1 + 1j, complex("nan"), 2 + 2j], + ], +) +def test_series_with_complex_nan(input_list): + # GH#53627 + ser = Series(input_list) + result = Series(ser.array) + assert ser.dtype == "complex128" + tm.assert_series_equal(ser, result)