Python TypeError:无法将非类别项附加到CategoricalIndex

Python TypeError:无法将非类别项附加到CategoricalIndex,python,python-2.7,pandas,merge,categorical-data,Python,Python 2.7,Pandas,Merge,Categorical Data,我无法合并数据帧,也无法理解为什么: 简单数据帧 df1 = pd.DataFrame({'id': np.random.randint(1,5,100), 'c': np.random.random(100), 's': np.random.random(100)}) 分成3组 grouped = pd.qcut(df1.c, 3) df_grouped = df1.groupby([grouped, 'id']

我无法合并数据帧,也无法理解为什么:

简单数据帧

df1 = pd.DataFrame({'id': np.random.randint(1,5,100),
                    'c': np.random.random(100),
                    's': np.random.random(100)})
分成3组

grouped = pd.qcut(df1.c, 3)
df_grouped = df1.groupby([grouped, 'id'])
df_cross = df_grouped['s'].sum()
df_unstacked = df_cross.unstack(level=0)
df_unstacked 
输出:

第二个简单数据帧:

df2 = pd.DataFrame({'one': range(5),
                   'two': np.random.randint(1,5,5),
                   'three': ['a', 'a', 'a', 'b', 'b']})

   one three two
0   0   a   4
1   1   a   2
2   2   a   1
3   3   b   2
4   4   b   2
正在尝试合并这两个:

pd.merge(df_unstacked, df2, left_index=True, right_on='one')
我希望:

c   [0.018, 0.372]  (0.372, 0.771]  (0.771, 0.995]  one three   two
id                      
1   3.081537    6.329819    3.386422    1   a   2
2   4.270542    2.553301    3.778536    2   a   1
3   3.125476    2.525016    3.013912    3   b   2
4   5.762223    3.763183    7.953551    4   b   2
但我得到了TypeError:

TypeError:无法将非类别项附加到CategoricalIndex

此外,尝试在df_unstacked上重置_index(),会出现TypeError:

TypeError:无法将项插入到尚未存在类别的CategoricalIndex中

创建.copy()没有帮助:)该怎么办


p、 s.pandas 0.17.1

实现此功能的一种方法是切换左右表的顺序。Pandas允许您将分类列连接到非分类列,但不能反过来连接

pd.merge(df2,df_unstacked, right_index=True, left_on='one')

您的
df_unstacked
列是分类的,您希望它如何处理
concat
?这就是错误出现的地方,现在我至少理解了问题:)老实说,我不确定你能绕过这个问题,除非你用str表示覆盖列,然后合并你是对的EdChum:df_unstacked.columns=df_unstacked.columns.astype(str)做trickleft_on=index_column_name
pd.merge(df2,df_unstacked, right_index=True, left_on='one')