近日,在做数据挖掘的时候使用了pandas来做数据的预处理,然而遇到了一个棘手的问题,就是 TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category。在百度找找不到解决方法,去github源码上也找不到解决方法,据说这是一个pandas的悬疑问题。后来实在是不能跳过这个坎,于是就自己捣鼓了。下面是我的错误:我在进行unstack方法后就想将原来变为索引的列转换为列,但是直接reset_index方法报错了!
这是我原报错的代码:
解决方法
#1.把原索引删除:
df = df.reset_index(drop=True)
#2.找到原索引原来的series:如我的用户id
userID = dataframe["userID].reset_index(drop=True) # dataframe为原来的df
# 再将两者拼接:
new_df = pd.concat([userID,df],axis=1)
然后现在生成的new_df就是原来直接df.reset_index()得到的了!!!