作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我无法合并数据帧并且无法理解为什么:
简单的数据框
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: cannot append a non-category item to a CategoricalIndex
此外,尝试在 df_unstacked 上重置_index() 会给出 TypeError:
TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category
创建 .copy() 没有帮助:)该怎么办?
附: Pandas 0.17.1
更新:
截至 2023 年,这些错误都不会出现。合并后列索引变为非分类索引。 Pandas 1.4.4
最佳答案
实现此目的的一种方法是交换左右表的顺序。 Pandas 允许您将分类列连接到非分类列,但反之则不然。
pd.merge(df2,df_unstacked, right_index=True, left_on='one')
关于python - 类型错误 : cannot append a non-category item to a CategoricalIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34901708/
我是一名优秀的程序员,十分优秀!