Pandas 中稀疏值列的数学运算会产生错误

问题描述 投票:0回答:1

在 pandas 中,我有一个数据框,我需要在其中生成两个虚拟矩阵,然后将一个虚拟矩阵的列添加到另一个虚拟矩阵。然而,pandas 似乎不支持两列稀疏值的数学运算。

# illustrative example
import pandas as pd

mat = [['cat','black',18],
       ['dog','brown',12],
       ['cat','tabby',9],
       ['mouse','brown',0.2]]
testframe = pd.DataFrame(mat, columns = ['animal','color','weight'])

# create a new dataframe of dummies with columns "cat", "dog", and "mouse"
animals = pd.get_dummies(testframe['animal'], sparse = True)

# the following does not create an error
animals['cat'] + 1

# this does
animals['cat'] + animals['dog']

运行最后一行时,出现错误

module 'pandas._libs.sparse' has no attribute 'sparse_add_uint8'

看来我仍然可以对稀疏值列执行标量操作;如前所述,我可以毫无问题地向此类列添加单个数字。但是,网上没有对错误消息进行扩展的结果。

我首先想到的解决方法是简单地转换为 SciPy 稀疏矩阵,然后再转换回 Pandas,但如果可能的话,我更愿意坚持使用 Pandas。

python pandas sparse-matrix
1个回答
0
投票

感谢@hpaulj,看来可以通过在创建虚拟值时要求

dtype = np.int64
来解决这个问题。希望 Pandas 的未来版本中不需要这样做。

© www.soinside.com 2019 - 2024. All rights reserved.