Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot set a Categorical with another, without identical categories. Replace almost identical categories

I have the following dataframe

np.random.seed(3)

s = pd.DataFrame((np.random.choice(['Feijão','feijão'],size=[3,2])),dtype='category')


print(s[0].cat.categories)
print(s[1].cat.categories)

As you can see the dataframe is basically two similar strings with one letter in uppercase. What I am trying to do is replace the category ‘feijão’ with ‘Feijão’

When I write the following line of code I get this error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

s.loc[s[0].isin(['feijão']),1] = s.loc[s[0].isin(['feijão']),1].replace({'feijão':'Feijão'})

TypeError: Cannot set a Categorical with another, without identical categories

I was wondering what does this error means, and also I am genuinely curious if filtering the invalid values and replacing them uniquely on the dataframe is the most optimal way of doing this. Should I just use replace without the filter part?

>Solution :

Use DataFrame.update:

s.update( s.loc[s[0].isin(['feijão']),1].replace({'feijão':'Feijão'}))
print (s)
        0       1
0  Feijão  Feijão
1  feijão  Feijão
2  Feijão  Feijão
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading