CategoricalDType列上的熊猫交叉表抛出TypeError

时间:2019-06-12 22:52:36

标签: python pandas categories crosstab

考虑这个简单的数据集,其列被分位数割断。

kyle = pd.DataFrame({'foo':np.random.randint(0,100,100),'boo':np.random.randint(0,100,100)})
kyle.loc[:,'fooCut'] = pd.qcut(kyle.loc[:,'foo'], np.arange(0,1.1,.1))
kyle.loc[:,'booCut'] = pd.qcut(kyle.loc[:,'boo'], np.arange(0,1.1,.1))

Pandas的早期版本按预期处理了以下内容...

pd.crosstab(kyle.fooCut,kyle.booCut)

更新为版本“ 0.24.2”后,以上内容使我抛出TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'

有人知道为什么以及如何解决这个问题吗? 请注意,此处kyle.boocut.dtype返回CategoricalDtype,其类型与分类变量的pd.crosstab documentation and example中的类型相同。

[更新]

这是熊猫中已知的bug,并且已修复

1 个答案:

答案 0 :(得分:1)

uncovered by OP一样,这是一个与透视有关的issuecrosstabpivot_table的优化版本)Interval列,目前已固定为v0 .25。

这是一种解决方法,涉及交叉制表整数代码:

cstab = pd.crosstab(kyle.fooCut.cat.codes, kyle.booCut.cat.codes)
cstab


col_0  0  1  2  3  4  5  6  7  8  9
row_0                              
0      0  2  0  1  3  1  2  1  1  1
1      1  1  0  1  1  2  1  0  1  2
2      2  1  1  0  1  1  2  0  0  0
3      2  1  3  1  2  0  0  0  0  1
4      1  2  1  0  0  2  0  1  1  2
5      0  2  0  1  0  1  0  3  3  0
6      2  0  1  2  0  2  1  1  1  1
7      1  0  0  2  2  0  1  1  2  0
8      0  1  1  0  1  1  3  1  1  1
9      1  1  2  2  0  0  2  1  0  1

如果愿意,您始终可以将结果的索引和列分配给实际类别:

cstab.index = kyle.fooCut.cat.categories
cstab.columns = kyle.booCut.cat.categories