Skip to content

Commit 767a9a7

Browse files
authored
BUG: Updated _pprint_seq to use enumerate instead of next (#57295)
1 parent 16e36dc commit 767a9a7

File tree

3 files changed

+18
-7
lines changed

3 files changed

+18
-7
lines changed

doc/source/whatsnew/v3.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ Performance improvements
141141
Bug fixes
142142
~~~~~~~~~
143143
- Fixed bug in :meth:`DataFrame.join` inconsistently setting result index name (:issue:`55815`)
144+
- Fixed bug in :meth:`DataFrame.to_string` that raised ``StopIteration`` with nested DataFrames. (:issue:`16098`)
144145
- Fixed bug in :meth:`Series.diff` allowing non-integer values for the ``periods`` argument. (:issue:`56607`)
145146

146147
Categorical

pandas/io/formats/printing.py

+10-7
Original file line numberDiff line numberDiff line change
@@ -111,19 +111,22 @@ def _pprint_seq(
111111
fmt = "[{body}]" if hasattr(seq, "__setitem__") else "({body})"
112112

113113
if max_seq_items is False:
114-
nitems = len(seq)
114+
max_items = None
115115
else:
116-
nitems = max_seq_items or get_option("max_seq_items") or len(seq)
116+
max_items = max_seq_items or get_option("max_seq_items") or len(seq)
117117

118118
s = iter(seq)
119119
# handle sets, no slicing
120-
r = [
121-
pprint_thing(next(s), _nest_lvl + 1, max_seq_items=max_seq_items, **kwds)
122-
for i in range(min(nitems, len(seq)))
123-
]
120+
r = []
121+
max_items_reached = False
122+
for i, item in enumerate(s):
123+
if (max_items is not None) and (i >= max_items):
124+
max_items_reached = True
125+
break
126+
r.append(pprint_thing(item, _nest_lvl + 1, max_seq_items=max_seq_items, **kwds))
124127
body = ", ".join(r)
125128

126-
if nitems < len(seq):
129+
if max_items_reached:
127130
body += ", ..."
128131
elif isinstance(seq, tuple) and len(seq) == 1:
129132
body += ","

pandas/tests/io/formats/test_to_string.py

+7
Original file line numberDiff line numberDiff line change
@@ -945,6 +945,13 @@ def test_to_string_repr_unicode(self):
945945
finally:
946946
sys.stdin = _stdin
947947

948+
def test_nested_dataframe(self):
949+
df1 = DataFrame({"level1": [["row1"], ["row2"]]})
950+
df2 = DataFrame({"level3": [{"level2": df1}]})
951+
result = df2.to_string()
952+
expected = " level3\n0 {'level2': ['level1']}"
953+
assert result == expected
954+
948955

949956
class TestSeriesToString:
950957
def test_to_string_without_index(self):

0 commit comments

Comments
 (0)