Skip to content

ENH: pd.cut should be able to return a Series of IntervalDtype #31459

Open
@Dr-Irv

Description

@Dr-Irv

Code Sample, a copy-pastable example if possible

In [1]: import pandas as pd

In [2]: import random

In [3]: df=pd.DataFrame({'x': [random.randint(0,10) for i in range(100)]})

In [4]: pd.cut(df.x, [2*i for i in range(6)])
Out[4]:
0      (6.0, 8.0]
1             NaN
2      (0.0, 2.0]
3      (2.0, 4.0]
4      (0.0, 2.0]
         ...
95    (8.0, 10.0]
96     (2.0, 4.0]
97    (8.0, 10.0]
98     (0.0, 2.0]
99    (8.0, 10.0]
Name: x, Length: 100, dtype: category
Categories (5, interval[int64]): [(0, 2] < (2, 4] < (4, 6] < (6, 8] < (8, 10]]

Problem description

By default, the return type of pd.cut is categories, but we know we are creating intervals, so shouldn't it be IntervalDtype ?

Expected Output

In [5]: pd.cut(df.x, [2*i for i in range(6)]).astype('Interval')
Out[5]:
0      (6.0, 8.0]
1             NaN
2      (0.0, 2.0]
3      (2.0, 4.0]
4      (0.0, 2.0]
         ...
95    (8.0, 10.0]
96     (2.0, 4.0]
97    (8.0, 10.0]
98     (0.0, 2.0]
99    (8.0, 10.0]
Name: x, Length: 100, dtype: interval

IMHO, I shouldn't need to do the 'astype('Interval')`

Output of pd.show_versions()

INSTALLED VERSIONS

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

pandas : 1.0.0
numpy : 1.17.4
pytz : 2019.3
dateutil : 2.8.1
pip : 19.3.1
setuptools : 42.0.2.post20191203
Cython : None
pytest : 5.3.2
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : 1.2.6
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.10.3
IPython : 7.11.1
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
pytest : 5.3.2
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : 1.2.0
xlwt : None
xlsxwriter : 1.2.6
numba : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementIntervalInterval data typeNeeds DiscussionRequires discussion from core team before further actioncutcut, qcut

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions