Skip to content

BUG: Adding colour code escape sequences to data values causes incorrect column spacing #55122

Open
@rufusbarnes

Description

@rufusbarnes

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

from io import StringIO
import pandas as pd

csv_string = ",0,1,2,3,4\nrow1,XXX,XXX,XXX,XXX,XXX\nrow2,XXX,XXX,XXX,XXX,XXX\nrow3,XXX,XXX,XXX,XXX,XXX"

df = pd.read_csv(StringIO(csv_string), index_col=False)

CYAN='\033[96m'
END='\033[0m'

df['0'].iloc[0] = CYAN + df['0'].iloc[0] + END

print(df)

Issue Description

When adding ansi colour code escape sequences to specific cells in a data frame, all rows not including the same sequence are spaced with the assumption that the maximum value length in that column is equal to the (length of the colour code) + (length of the value) resulting in incorrect spacing in rows without the colour code present.

Expected Behavior

Columns should not include the colour code escape sequence in their total width.

Installed Versions

INSTALLED VERSIONS

commit : ba1cccd
python : 3.11.5.final.0
python-bits : 64
OS : Darwin
OS-release : 22.6.0
Version : Darwin Kernel Version 22.6.0: Wed Jul 5 22:21:53 PDT 2023; root:xnu-8796.141.3~6/RELEASE_ARM64_T6020
machine : arm64
processor : arm
byteorder : little
LC_ALL : None
LANG : en_GB.UTF-8
LOCALE : en_GB.UTF-8

pandas : 2.1.0
numpy : 1.25.2
pytz : 2023.3.post1
dateutil : 2.8.2
setuptools : 68.1.2
pip : 23.2.1
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.15.0
pandas_datareader : None
bs4 : None
bottleneck : None
dataframe-api-compat: None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions