cannot use inplace with CategoricalIndex

74 views
Skip to first unread message

Kent Maxwell

unread,
Sep 10, 2018, 6:15:35 PM9/10/18
to PyData
Hello,

I am using pandas version 0.23.4.

The documentation at https://pandas.pydata.org/pandas-docs/stable/generated/pandas.CategoricalIndex.add_categories.html suggests that it is possible to add categories to a CategoricalIndex in place.  However, when I try to use this code:

import pandas as pd


test_df
= pd.DataFrame({'Month':['January', 'February', 'March', 'March'], 'Values':[0,1,2,3]})
test_df
['Month'] = pd.Categorical(test_df['Month'], categories=['January', 'February', 'March'])
test_df
.set_index(['Month'])
test_df
.set_index(['Month'], inplace=True)
test_df
.index.add_categories(new_categories='April', inplace=True)

I get this error:

ValueError: cannot use inplace with CategoricalIndex


Anyone know what I am doing wrong?  Anyone know how I can add a category into a CategoricalIndex not in place?

Thanks,

Kent

Paul Hobson

unread,
Sep 10, 2018, 7:38:41 PM9/10/18
to pyd...@googlegroups.com
Like the error says, you can't add categories with  inplace=True .

So do  inplace=False and capture the return value:

test_df  = test_df.reindex(test_df.index.add_categories(new_categories='April', inplace=False))

Better yet, chain all of this into one statement:

test_df = (

    pd.DataFrame({'Month':['January', 'February', 'March', 'March'], 'Values':[0,1,2,3]})
      .assign(Month=lambda df: pd.Categorical(

          df['Month'],
          categories=['January', 'February', 'March']
       ).add_categories(new_categories='April'))
      .set_index('Month')
)

print(test_df.to_string())
print(test_df.index)

And that give me:
          Values
Month           
January        0
February       1
March          2
March          3
CategoricalIndex(['January', 'February', 'March', 'March'],
categories=['January', 'February', 'March', 'April'],
ordered=False,
name='Month',
dtype='category')

Note: I don't recommend setting the index to a column with duplicate values. But it's hard to recommend anything pertaining to that without more context.
-Paul


--
You received this message because you are subscribed to the Google Groups "PyData" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pydata+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages