Skip to content

Backport PR #54801 on branch 2.1.x (BUG: repr aligning left for string dtype columns) #54819

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,7 @@ Conversion
Strings
^^^^^^^
- Bug in :meth:`Series.str` that did not raise a ``TypeError`` when iterated (:issue:`54173`)
- Bug in ``repr`` for :class:`DataFrame`` with string-dtype columns (:issue:`54797`)

Interval
^^^^^^^^
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1419,8 +1419,8 @@ def _format_with_header(self, header: list[str_t], na_rep: str_t) -> list[str_t]

values = self._values

if is_object_dtype(values.dtype):
values = cast(np.ndarray, values)
if is_object_dtype(values.dtype) or is_string_dtype(values.dtype):
values = np.asarray(values)
values = lib.maybe_convert_objects(values, safe=True)

result = [pprint_thing(x, escape_chars=("\t", "\r", "\n")) for x in values]
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/frame/test_repr_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,3 +455,14 @@ def test_masked_ea_with_formatter(self):
0 0.12 1.00
1 1.12 2.00"""
assert result == expected

def test_repr_ea_columns(self, any_string_dtype):
# GH#54797
pytest.importorskip("pyarrow")
df = DataFrame({"long_column_name": [1, 2, 3], "col2": [4, 5, 6]})
df.columns = df.columns.astype(any_string_dtype)
expected = """ long_column_name col2
0 1 4
1 2 5
2 3 6"""
assert repr(df) == expected