gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:41:05 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com