Skip to content

BUG: sort_values create an unprintable object #39426

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

Closed
2 of 3 tasks
gshimansky opened this issue Jan 26, 2021 · 7 comments · Fixed by #39464
Closed
2 of 3 tasks

BUG: sort_values create an unprintable object #39426

gshimansky opened this issue Jan 26, 2021 · 7 comments · Fixed by #39464
Assignees
Milestone

Comments

@gshimansky
Copy link

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

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

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

# Your code here
import pandas as pd
import numpy as np

RAND_LOW = 0
RAND_HIGH = 100
NCOLS = 2 ** 5
NROWS = 2 ** 2

random_state = np.random.RandomState(seed=42)
data = {
    "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.randint(
        RAND_LOW, RAND_HIGH, size=(NROWS)
    )
    for i in range(NCOLS)
}
df1 = pd.DataFrame(data)
print(df1)
df2 = df1.sort_values(df1.index[0], axis=1, ignore_index=True)
print(df2)

Problem description

[this should explain why the current behaviour is a problem and why the expected output is a better solution]
Printing object returned by sort_values produces an exception because some internal metadata is wrong:

Traceback (most recent call last):
  File "sort_values_test6.py", line 19, in <module>
    print(df2)
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/core/frame.py", line 803, in __repr__
    self.to_string(
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/core/frame.py", line 939, in to_string
    return fmt.DataFrameRenderer(formatter).to_string(
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/io/formats/format.py", line 1031, in to_string
    string = string_formatter.to_string()
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/io/formats/string.py", line 23, in to_string
    text = self._get_string_representation()
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/io/formats/string.py", line 47, in _get_string_representation
    return self._fit_strcols_to_terminal_width(strcols)
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/io/formats/string.py", line 179, in _fit_strcols_to_terminal_width
    self.fmt.truncate()
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/io/formats/format.py", line 700, in truncate
    self._truncate_horizontally()
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/io/formats/format.py", line 718, in _truncate_horizontally
    self.tr_frame = concat((left, right), axis=1)
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/core/reshape/concat.py", line 298, in concat
    return op.get_result()
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/core/reshape/concat.py", line 520, in get_result
    new_data = concatenate_block_managers(
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/core/internals/concat.py", line 89, in concatenate_block_managers
    return BlockManager(blocks, axes)
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/core/internals/managers.py", line 143, in __init__
    self._verify_integrity()
  File "/localdisk/gashiman/miniconda3/lib/python3.8/site-packages/pandas/core/internals/managers.py", line 323, in _verify_integrity
    raise construction_error(tot_items, block.shape[1:], self.axes)
ValueError: Shape of passed values is (4, 16), indices imply (32, 16)

Expected Output

Output of pd.show_versions()

[paste the output of pd.show_versions() here leaving a blank line after the details tag]
INSTALLED VERSIONS

commit : 9d598a5
python : 3.8.6.final.0
python-bits : 64
OS : Linux
OS-release : 5.4.0-56-generic
Version : #62-Ubuntu SMP Mon Nov 23 19:20:19 UTC 2020
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.2.1
numpy : 1.19.4
pytz : 2020.1
dateutil : 2.8.1
pip : 20.3.1
setuptools : 49.6.0.post20201009
Cython : None
pytest : 6.2.1
hypothesis : None
sphinx : None
blosc : None
feather : 0.4.1
xlsxwriter : None
lxml.etree : 4.6.2
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.18.1
pandas_datareader: None
bs4 : 4.9.3
bottleneck : None
fsspec : 0.8.4
fastparquet : None
gcsfs : None
matplotlib : 3.2.2
numexpr : 2.7.1
odfpy : None
openpyxl : 3.0.5
pandas_gbq : 0.14.1
pyarrow : 2.0.0
pyxlsb : None
s3fs : 0.5.2
scipy : 1.5.4
sqlalchemy : 1.3.21
tables : 3.6.1
tabulate : None
xarray : 0.16.2
xlrd : 2.0.1
xlwt : None
numba : None

@gshimansky gshimansky added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Jan 26, 2021
@gshimansky
Copy link
Author

Also shape of DataFrame changes with this sort_values call, which doesn't seem to be right. Original DataFrame has shape (4, 32) and sorted DataFrame has shape (32, 32).

@phofl
Copy link
Member

phofl commented Jan 26, 2021

On master this is already raising with sort values

Traceback (most recent call last):
  File "/home/developer/.config/JetBrains/PyCharm2020.3/scratches/scratch_4.py", line 409, in <module>
    df2 = df1.sort_values(df1.index[0], axis=1, ignore_index=True)
  File "/home/developer/PycharmProjects/pandas/pandas/core/frame.py", line 5551, in sort_values
    new_data.set_axis(1, ibase.default_index(len(indexer)))
  File "/home/developer/PycharmProjects/pandas/pandas/core/internals/managers.py", line 224, in set_axis
    raise ValueError(
ValueError: Length mismatch: Expected axis has 4 elements, new values have 32 elements

Process finished with exit code 1

@attack68
Copy link
Contributor

if you remove ignore_index=True then this works. From the looks of it this recent argument is maybe trying to refit the index, when the columns have been sorted:

5550:        if ignore_index:
5551:            new_data.set_axis(1, ibase.default_index(len(indexer)))

If you change this to:

5550:        if ignore_index:
5551:            new_data.set_axis(1-axis, ibase.default_index(len(indexer)))

then you do actually get the result you want.

@gshimansky
Copy link
Author

Yes I know that it works with ignore_index=False. Also this test is sensitive of df1.columns contents. It is not a matter of performing this operation for me, it is a matter of correct implementation in Pandas. This bug was found by Modin project tests on sort_values. We need a correctly working Pandas function to implement this in Modin.

@attack68
Copy link
Contributor

I provided the solution to correctly implement in Pandas, feel free to submit PR and check it satisfies all tests

@jorisvandenbossche jorisvandenbossche added good first issue and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Jan 27, 2021
@jorisvandenbossche
Copy link
Member

Instead of the 1 - axis, we should probably use self._get_block_manager_axis(axis) (which basically does the same, but with the helper function that is meant for this).

@jorisvandenbossche jorisvandenbossche added this to the Contributions Welcome milestone Jan 27, 2021
@zitorelova
Copy link
Contributor

take

@jreback jreback modified the milestones: Contributions Welcome, 1.3 Feb 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants