Skip to content

IndexError is raised when printing wide dataframes on too narrow terminal #21327

Closed
@pevoz23

Description

@pevoz23

Code Sample, a copy-pastable example if possible

Execute this code in a terminal with width <= 90 cols.

import pandas as pd
val = [1017.56, 88.0502014, 114.90493799999999, 98.52555079999999, -4.35584164,
 0.13409058699999998, -3.28222513, 0.137214884, -3.23924017, 0.08030553160000001,
 25.4253311, 4.71156263, 4.71156263, 4.71148443, 0.725787282, 0.861985624,
 0.488319486, 0.221756965, 0.491590142, 0.174637929, 0.14585168699999998,
 0.8847839829999999, pd.Timestamp('2018-05-08 20:07:23.560000')]
col_id = pd.MultiIndex(levels=[['A', 'B', 'C', 'D', 'E', 'F'],
	['0', '1', '2', '3', '4', '5', '6', '7', 'a', 'act', 'axl', 'b', 'c', 'top', ''], 
        ['a', 'b', 'c', '']],
        labels=[[4, 0, 0, 0, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 5],
	[-1, 8, 11, 12, 10, 13, 10, 13, 10, 13, -1, 9, 9, 9, 0, 1, 2, 3, 4, 5, 6, 7, 14],
	[-1, -1, -1, -1, 0, 0, 1, 1, 2, 2, -1, 0, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, 3]])
row_id = pd.MultiIndex.from_tuples(
        [('rotation', '0', pd.Timedelta('0 days 01:20:01.807984'))])
df = pd.DataFrame(data=val).transpose()
df.index = row_id
df.columns = col_id
print(df)

Problem description

When trying to print a dataframe, if the values contained in the indexes and/or in the first/last column are too long and the terminal too narrow, an IndexError is raised:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/base.py", line 61, in __str__
    return self.__unicode__()
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py", line 663, in __unicode__
    line_width=width, show_dimensions=show_dimensions)
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py", line 1968, in to_string
    formatter.to_string()
  File "/usr/local/lib/python3.6/dist-packages/pandas/io/formats/format.py", line 648, in to_string
    strcols = self._to_str_columns()
  File "/usr/local/lib/python3.6/dist-packages/pandas/io/formats/format.py", line 539, in _to_str_columns
    str_columns = self._get_formatted_column_labels(frame)
  File "/usr/local/lib/python3.6/dist-packages/pandas/io/formats/format.py", line 782, in _get_formatted_column_labels
    str_columns = _sparsify(str_columns)
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/multi.py", line 2962, in _sparsify
    prev = pivoted[start]
IndexError: list index out of range

This happens because pandas.io.formats.format.DataFrameFormatter._chk_truncate() gives an empty frame. Subsequently, an empty str_columns is passed to pandas.core.indexes.multi._sparsify(*args) which raises the IndexError when trying to access the passed variable.

This problem seems to arise only when the dataframe and its index contains datetime-like values (see example with long strings in next section).

Expected Output

The raised exception is misleading, since the user could think his/her dataframe has something wrong, whereas only the size of the terminal is too narrow. A proper slicing of the string version of datetime formats in order to fit the terminal size would be the expected output.

With strings, this works better than with datetime. The following code does not raise any Exception:

n = 10
rng = pd.date_range('22/12/2018', periods=n, freq='H')
id_1 = ["i am a really long string"]*n
["Lorem ipsum dolor sit amet, consectetur adipiscing elit"+str(i) for i in range(n)]
ids = pd.MultiIndex.from_tuples(list(zip(id_1,id_2,rng)))
df = pd.DataFrame([rng,rng]).transpose()
df.index = ids
print(df)

Otherwise, a warning with an explanation should be raised if the frame that has to be printed gets truncated to an empty one.

Output of pd.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.6.5.final.0
python-bits: 64
OS: Linux
OS-release: 4.15.0-22-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.23.0
pytest: None
pip: 9.0.1
setuptools: 39.2.0
Cython: 0.28.3
numpy: 1.14.3
scipy: 1.1.0
pyarrow: None
xarray: None
IPython: 6.4.0
sphinx: 1.6.7
patsy: None
dateutil: 2.7.3
pytz: 2018.4
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 2.2.2
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: 0.999999999
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: 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