为什么 pandas sum() 对稀疏数据框给出错误的答案?

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

Sparse
数据框中,应用于整个数据框的
sum()
方法会给出错误的结果,而应用于特定列或数据框子集的
sum()
则有效。

当应用于整个数据帧时,它看起来像是

sum()
的溢出问题,因为选择类型
Sparse[int8, 0]
作为求和结果。但是,为什么其他两种情况不是这样呢?

注意:奇怪的是,当在 Anaconda 终端中运行时,每个场景都会给出正确的结果,而在 Pycharms 中我会看到错误。

>>> import numpy as np
>>> import pandas as pd

>>> # Generate standard and sparse DF with binary variable.
>>> # Use int8 to minimize memory usage.
>>> df = pd.DataFrame(np.random.randint(low=0, high=2, size=(50_000, 1)))
>>> sdf = df.astype(pd.SparseDtype(dtype='int8', fill_value=0))
>>> print(df.sum(axis=0))
0    24954
dtype: int64

>>> # Why does this give a wrong answer while the other two work?
>>> print(sdf.sum(axis=0))
0    122
dtype: Sparse[int8, 0]

>>> # Works
>>> print(sdf[0].sum())
24954

>>> # Works
>>> print(sdf[sdf==1].sum())
0    24954.0
dtype: float64

最后,在不密集或不更改

dtype
的情况下对稀疏 df 列进行求和的安全方法是什么?我目前迭代每一列并将
sum()
结果保存在字典中(类似于本例中的场景2),然后转换为dataframe,这看起来有点麻烦。

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

不幸的是,我认为你的问题可能没有好的答案。如果我必须处理稀疏矩阵,我宁愿使用scipy

import pandas as pd
from scipy.sparse import csr_matrix

df = pd.DataFrame(np.random.randint(low=0, high=2, size=(50_000, 3)))
sdf = csr_matrix(df, dtype='int8')
>>> sdf 
<50000x3 sparse matrix of type '<class 'numpy.int8'>'
    with 75298 stored elements in Compressed Sparse Row format>

>>> sdf.sum(axis=0)
matrix([[24963, 25202, 25133]])

>>> pd.DataFrame(sdf.sum(axis=0), columns=df.columns)
       0      1      2
0  24963  25202  25133

但是,请注意 Pandas 会员开的票:DEPR:SparseDtype #56518

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