Skip to content

Cannot remove_unused_categories for CategoricalIndex in a MultiIndex #30846

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

Open
fujiisoup opened this issue Jan 9, 2020 · 6 comments
Open
Labels
Bug Categorical Categorical Data Type MultiIndex

Comments

@fujiisoup
Copy link

I'm working to add a CategoricalIndex support in xarray (pydata/xarray#3647, pydata/xarray#3670), but have a trouble.

Code Sample, a copy-pastable example if possible

In [39]: cat = pd.CategoricalDtype(categories=['foo', 'bar', 'baz']) 
    ...: i1 = pd.Series(['foo', 'bar'], dtype=cat) 
    ...: i2 = pd.Series(['bar', 'bar'], dtype=cat) 
    ...: df = pd.DataFrame({'i1': i1, 'i2': i2, 'values': [1, 2]}) 

In [40]: df1 = df.set_index('i1')                                               
In [42]: df1.index                                                              
Out[42]: CategoricalIndex(['foo', 'bar'], 
        categories=['foo', 'bar', 'baz'], ordered=False, name='i1', dtype='category')

# remove_unused_categories() is working
In [43]: df1.index.remove_unused_categories()                                   
Out[43]: CategoricalIndex(['foo', 'bar'], 
        categories=['foo', 'bar'], ordered=False, name='i1', dtype='category')

In [44]: df2 = df.set_index(['i1', 'i2'])                                       
In [45]: df2.index                                                              
Out[45]: 
MultiIndex([('foo', 'bar'),
            ('bar', 'bar')],
           names=['i1', 'i2'])

# remove_unused_categories() is NOT working
In [47]: df2.index.levels[0].remove_unused_categories()                         
Out[47]: CategoricalIndex(['foo', 'bar', 'baz'], 
        categories=['foo', 'bar', 'baz'], ordered=False, name='i1', dtype='category')  # <-- `baz` is not removed.

Problem description

When CategoricalIndex is a level variable of MultiIndex, remove_unused_categories does not work.

Expected Output

Out[43]: CategoricalIndex(['foo', 'bar'], categories=['foo', 'bar'], ordered=False, name='i1', dtype='category')

Output of pd.show_versions()

In [48]: pd.show_versions()

INSTALLED VERSIONS

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

pandas : 0.25.3
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 : 4.54.2
sphinx : 2.3.0
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : 1.0.1
pymysql : None
psycopg2 : None
jinja2 : 2.10.3
IPython : 7.10.2
pandas_datareader: None
bs4 : None
bottleneck : 1.3.1
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : 3.1.1
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
s3fs : None
scipy : 1.3.2
sqlalchemy : None
tables : None
xarray : 0.14.1
xlrd : 1.2.0
xlwt : None
xlsxwriter : None

@TomAugspurger
Copy link
Contributor

Hmm, thanks for the report @fujiisoup. There's been some changes to how MI levels are handled, but it doesn't seem to fix this issue.

In this line,

df2.index.levels[0].remove_unused_categories()

The CategoricalIndex accessed via .levels[0] is ephemeral. The changes to it won't reflect back to df2.index. Do we need an API like MultiIndex.remove_unused_categories that applies to levels of a MultiIndex that are Categorical?

cc @topper-123.

@fujiisoup
Copy link
Author

Thanks, @TomAugspurger, for your quick reply.

Do we need an API like MultiIndex.remove_unused_categories that applies to levels of a MultiIndex
that are Categorical?

Yes, it would be nice.
I also tried with inplace=True, but it says

ValueError: cannot use inplace with CategoricalIndex

@topper-123
Copy link
Contributor

topper-123 commented Jan 9, 2020

IMO this works as intended as an ops on a single level is not intended to affect the whole MultiIndex. If you want to create an MultiIndex with unused categories removed, they currently need to be removed before creating the MultiIndex.

This may not be very intuitive, but I'm not sure what to change. The workflow "Creating a new MultiIndex from an existing MultiIndex, but with some levels changed" is probably difficult to implement as a method. The best current approach is probably to extract the arrays to a DataFrame using MultiIndex.to_frame, doing the needed changed on the DataFrame columns, then use MultiIndex.from_frame to turn the DataFrame content into a MultiIndex.

I BTW have a branch where I'm trying to implement #27138, which would give us MultiIndex.arrays to mirror Index.array etc. That would give us easy access to the individual levels as Categoricals. But I am not making progress ATM, so IDK when that will land.

@TomAugspurger
Copy link
Contributor

TomAugspurger commented Jan 9, 2020 via email

@topper-123
Copy link
Contributor

I don't like it because it's too specific; There so many other level-changing methods that could be added that it seems arbitrary to add just that one IMO. Maybe if some more general could be found?

@fujiisoup
Copy link
Author

Thanks all.
What we want to do is actually

full_idx = pd.MultiIndex.from_product(idx.levels, names=idx.names)

and

shape = tuple(lev.size for lev in idx.levels)

only with used levels.

Is there any good workaround for this?
Currently, I am doing

levels = []
for i, level in enumerate(index.levels):
    if isinstance(level, pd.CategoricalIndex):
        level = level[index.codes[i]].remove_unused_categories()
    levels.append(level)
index = pd.MultiIndex.from_arrays(levels, names=index.names)

which is not very beutiful.

@jbrockmendel jbrockmendel added the Categorical Categorical Data Type label Feb 25, 2020
@mroeschke mroeschke added the Bug label Jun 28, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Categorical Categorical Data Type MultiIndex
Projects
None yet
Development

No branches or pull requests

5 participants