Skip to content

BUG: repr aligning left for string dtype columns #54801

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 2 commits into from
Aug 28, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 2 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1395,6 +1395,8 @@ def _format_with_header(self, header: list[str_t], na_rep: str_t) -> list[str_t]
from pandas.io.formats.format import format_array

values = self._values
if is_string_dtype(values.dtype):
values = np.asarray(values)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if is_string_dtype(values.dtype):
values = np.asarray(values)
if is_string_dtype(values.dtype):
# ensure we have an object dtype numpy array
values = np.asarray(values)


if is_object_dtype(values.dtype):
values = cast(np.ndarray, 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