Error: astype() got an unexpected keyword argument 'categories'

Kak*_*t_7 6 python pandas

 df = pd.DataFrame(['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D'],
                      index=['excellent', 'excellent', 'excellent', 'good', 'good', 'good', 'ok', 'ok', 'ok', 'poor', 'poor'])
    df.rename(columns={0: 'Grades'}, inplace=True)
    df
Run Code Online (Sandbox Code Playgroud)

I am trying to create an ordered category from the above dataframe using the following code -

df = df['Grades'].astype('category',categories=['D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'],ordered=True)
Run Code Online (Sandbox Code Playgroud)

However it gives the error : astype() got an unexpected keyword argument 'categories'.

jez*_*ael 8

From pandas 0.25+ are removed these arguments:

Removed the previously deprecated ordered and categories keyword arguments in astype (GH17742)


In newer pandas versions is necesary use CategoricalDtype and pass to astype:

from pandas.api.types import CategoricalDtype

cats = ['D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+']
cat_type = CategoricalDtype(categories=cats, ordered=True)
df['Grades'] = df['Grades'].astype(cat_type)
print (df)
             Grades
excellent     A+
excellent      A
excellent     A-
good          B+
good           B
good          B-
ok            C+
ok             C
ok            C-
poor          D+
poor           D
Run Code Online (Sandbox Code Playgroud)

Or use Categorical:

df['Grades'] = pd.Categorical(df['Grades'], categories=cats, ordered=True)
print (df)
             Grades
excellent     A+
excellent      A
excellent     A-
good          B+
good           B
good          B-
ok            C+
ok             C
ok            C-
poor          D+
poor           D
Run Code Online (Sandbox Code Playgroud)