Skip to content
Advertisement

pandas Categorical error: “Cannot setitem on a Categorical with a new category, set the categories first”

I have the following df data frame in pandas:

JavaScript

What I want to do is to order the data frame by the following days’ order:

JavaScript

To do so, I used the following code:

JavaScript

When I run the code, I get this error:

JavaScript

I have not found enough documentation to resolve this. Can you help me? Thanks!

Advertisement

Answer

df[['weekday']] returns a dataframe, which is incorrect. Convert the series column to categorical instead. Also, use the ordered=True argument to establish order in your categorical column.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement