错误:astype() 收到意外的关键字参数“类别”

2024-01-19

 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

我正在尝试使用以下代码从上面的数据帧创建一个有序类别 -

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

但是它给出了错误:astype() 收到意外的关键字参数“categories”.


来自熊猫0.25+删除了这些参数 https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.25.0.html#removal-of-prior-version-deprecations-changes:

删除了之前已弃用的 astype 中的ordered和categories关键字参数(GH17742)


在较新的 pandas 版本中需要使用CategoricalDtype https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#controlling-behavior并传递给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

Or use Categorical http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Categorical.html:

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

错误:astype() 收到意外的关键字参数“类别” 的相关文章

随机推荐