【问题标题】:TypeError: cannot append a non-category item to a CategoricalIndexTypeError:无法将非类别项目附加到 CategoricalIndex
【发布时间】:2016-04-26 09:31:59
【问题描述】:

我无法合并数据框,也无法理解原因:

简单的数据框

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 

输出:

c   [0.018, 0.372]  (0.372, 0.771]  (0.771, 0.995]
id          
1   3.081537    6.329819    3.386422
2   4.270542    2.553301    3.778536
3   3.125476    2.525016    3.013912
4   5.762223    3.763183    7.953551

第二个简单的数据框:

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: 无法将非类别项目附加到 CategoricalIndex

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

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

制作 .copy() 没有帮助:) 该怎么办?

附言熊猫 0.17.1

【问题讨论】:

  • 您的df_unstacked 列是分类的,您希望它如何处理concat?这是出现错误的地方
  • Thanx EdChum,现在我至少明白了这个问题:)
  • 老实说,我不确定你是否能解决这个问题,除非你用 str 表示覆盖列然后合并
  • 你是对的 EdChum:df_unstacked.columns = df_unstacked.columns.astype(str) 成功了

标签: python python-2.7 pandas merge categorical-data


【解决方案1】:

执行的操作导致df_unstacked的列标签为CategoricalIndex;而df2.columns 是一个简单的Index。在合并操作期间,两个列标签也将被合并(无论如何都会导致Index)。我猜这个实现并没有解决第一列标签可以是CategoricalIndex的场景。

如果您不想颠倒合并的顺序,我建议将CategoricalIndex 更改为Index

df_unstacked.columns = df_unstacked.columns.to_list()
pd.merge(df_unstacked, df2, left_index=True, right_on='one')

【讨论】:

    【解决方案2】:

    实现这项工作的一种方法是切换左右表的顺序。 Pandas 允许您将分类列连接到非分类列,但反之则不行。

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

    【讨论】:

    • left_on = index_column_name
    猜你喜欢
    • 2020-06-21
    • 1970-01-01
    • 2015-05-23
    • 2016-01-23
    • 2015-03-17
    • 2016-11-22
    • 2021-07-09
    • 2016-05-14
    • 1970-01-01
    相关资源
    最近更新 更多