python - Pandas 分类错误 : "Cannot setitem on a Categorical with a new category, set the categories first"

标签 python pandas categorical-data

我在 pandas 中有以下 df 数据框:

    weekday  venta_total_cy
0   Viernes    5.430211e+09
1     Lunes    3.425554e+09
2     Sabado    6.833202e+09
3   Domingo    6.566466e+09
4    Jueves    2.748710e+09
5    Martes    3.328418e+09
6  Miercoles    3.136277e+09

我想做的是按照接下来几天的顺序来订购数据框:

weekday
Lunes
Martes
Miercoles
Jueves
Viernes
Sabado
Domingo

为此,我使用了以下代码:

df['weekday'] = pd.Categorical(df[['weekday']], categories=["Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo"])

当我运行代码时,出现以下错误:

ValueError: Cannot setitem on a Categorical with a new category, set the categories first

我没有找到足够的文档来解决这个问题。你能帮助我吗?谢谢!

最佳答案

df[['weekday']] 返回一个不正确的数据框。将 series 列转换为分类列。此外,使用 ordered=True 参数在您的分类列中建立顺序。

categories = np.array(
     ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado', 'Domingo'])

df['weekday'] = pd.Categorical(
   df['weekday'], categories=categories, ordered=True)
df.sort_values(by='weekday')

     weekday  venta_total_cy
1      Lunes    3.425554e+09
5     Martes    3.328418e+09
6  Miercoles    3.136277e+09
4     Jueves    2.748710e+09
0    Viernes    5.430211e+09
2     Sabado    6.833202e+09
3    Domingo    6.566466e+09

关于python - Pandas 分类错误 : "Cannot setitem on a Categorical with a new category, set the categories first",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49197386/

相关文章:

python - 使用 textblob 或 spacy 更正法语拼写

Python 单词的首字母大写

python - 用Python读取一个excel文件,在不改变样式的情况下进行修改

python - pandas 中的方法链接时如何引用中间数据框?

python - 词汇散布图是seaborn

python - 新鲜的bash shell-未安装-如何安装命令

python数组包含切片索引

python - Matplotlib:从主轴映射值的次轴

python - 如何在Python中将时间转换为类别?

python - 使用 Pandas 将分类值转换为二进制