diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 705c335acfb48..b010b71abab3f 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -249,6 +249,7 @@ Other instead of ``TypeError: Can only append a Series if ignore_index=True or if the Series has a name`` (:issue:`30871`) - Set operations on an object-dtype :class:`Index` now always return object-dtype results (:issue:`31401`) - Bug in :meth:`AbstractHolidayCalendar.holidays` when no rules were defined (:issue:`31415`) +- Bug in :meth:`DataFrame.itertuples` was returning empty list when DataFrame has no columns (:issue:`25408`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 7efb4fbb878d6..ed49f750d2061 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1027,7 +1027,11 @@ def itertuples(self, index=True, name="Pandas"): fields.insert(0, "Index") # use integer indexing because of possible duplicate column names - arrays.extend(self.iloc[:, k] for k in range(len(self.columns))) + if len(self.columns) > 0: + arrays.extend(self.iloc[:, k] for k in range(len(self.columns))) + else: + arrays.extend([() for _ in range(len(self))]) + return iter(arrays) # Python versions before 3.7 support at most 255 arguments to constructors can_return_named_tuples = PY37 or len(self.columns) + index < 255 diff --git a/pandas/tests/frame/methods/test_to_dict.py b/pandas/tests/frame/methods/test_to_dict.py index cd9bd169322fd..a934dffa763fd 100644 --- a/pandas/tests/frame/methods/test_to_dict.py +++ b/pandas/tests/frame/methods/test_to_dict.py @@ -262,3 +262,10 @@ def test_to_dict_orient_dtype(self): "c": type(df_dict["c"]), } assert result == expected + + def test_to_dict_no_rows_split(self): + # GH 25408 + columns = ["A", "B"] + result = DataFrame(columns=columns).transpose().to_dict(orient="split") + expected = {"index": ["A", "B"], "columns": [], "data": [[], []]} + assert result == expected diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index a021dd91a7d26..bf52e54695a15 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -286,6 +286,12 @@ def test_itertuples(self, float_frame): else: assert not hasattr(result_255_columns, "_fields") + # GH 25408 + df_0_columns = DataFrame(index=["A", "B"]) + result = list(df_0_columns.itertuples()) + tm.assert_index_equal(result[0], pd.Index(["A", "B"])) + assert result[1:] == [(), ()] + def test_sequence_like_with_categorical(self): # GH 7839