diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index a0c5b4523f782..fb016defc0c56 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -731,6 +731,7 @@ I/O - Bug in :func:`read_sql` when reading multiple timezone aware columns with the same column name (:issue:`44421`) - Bug in :func:`read_xml` stripping whitespace in string data (:issue:`53811`) - Bug in :meth:`DataFrame.to_html` where ``colspace`` was incorrectly applied in case of multi index columns (:issue:`53885`) +- Bug in :meth:`DataFrame.to_html` where conversion for an empty :class:`DataFrame` with complex dtype raised a ``ValueError`` (:issue:`54167`) - Bug in :meth:`DataFrame.to_json` where :class:`DateTimeArray`/:class:`DateTimeIndex` with non nanosecond precision could not be serialized correctly (:issue:`53686`) - Bug when writing and reading empty Stata dta files where dtype information was lost (:issue:`46240`) - Bug where ``bz2`` was treated as a hard requirement (:issue:`53857`) diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index a7a6f481ebdde..9fe8cbfa159c6 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1960,6 +1960,8 @@ def _trim_zeros_complex(str_complexes: np.ndarray, decimal: str = ".") -> list[s # in the array n = len(str_complexes) padded_parts = _trim_zeros_float(real_part + imag_part, decimal) + if len(padded_parts) == 0: + return [] padded_length = max(len(part) for part in padded_parts) - 1 padded = [ real_pt # real part, possibly NaN diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py index 13041623f4aa6..3b5fe329c320c 100644 --- a/pandas/tests/io/formats/test_to_html.py +++ b/pandas/tests/io/formats/test_to_html.py @@ -959,3 +959,22 @@ def test_to_html_tuple_col_with_colspace(): "" ) assert result == expected + + +def test_to_html_empty_complex_array(): + # GH#54167 + df = DataFrame({"x": np.array([], dtype="complex")}) + result = df.to_html(col_space=100) + expected = ( + '
\n' + ' | x | \n' + "
---|