Pandas cut method gives an error if labels are non-unique · Issue #33141 · pandas-dev/pandas (original) (raw)

Code Sample, a copy-pastable example if possible

import pandas as pd data = pd.DataFrame({'morf':[8142, 8153, 8161]}) bins = [8140, 8150, 8160, 8163] labels = ['Adenocarcinomas', 'Other specific carcinomas', 'Adenocarcinomas']

data['group'] = pd.cut(data['morf'], bins, labels=labels)

Problem description

I want to use pandas cut to fill in labels for ranges that are scattered. E.g. I want to map the following table onto my data, where the definitions span ranges that are scattered across the morphology continuum:
image

The above code gives the error:
ValueError: Categorical categories must be unique

Expected Output

I expect the example above to run and give back the labeled dataframe without an error.

My workaround is to add the index to the labels and then remove that again after the cut.

Output of pd.show_versions()

[paste the output of pd.show_versions() here below this line]

INSTALLED VERSIONS

commit : None
python : 3.7.6.final.0
python-bits : 64
OS : Windows
OS-release : 10
machine : AMD64
processor : Intel64 Family 6 Model 142 Stepping 10, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.None

pandas : 1.0.1
numpy : 1.18.1
pytz : 2019.3
dateutil : 2.8.1
pip : 20.0.2
setuptools : 45.2.0.post20200209
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.1
IPython : 7.12.0
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : 3.1.3
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
pytest : None
pyxlsb : None
s3fs : None
scipy : 1.4.1
sqlalchemy : None
tables : None
tabulate : None
xarray : 0.15.0
xlrd : 1.2.0
xlwt : None
xlsxwriter : None
numba : 0.48.0