Pandas:如何减去稀疏数据帧的平均列?

Pandas: how to subtract the mean column of a sparse dataframe?

在 pandas 0.25.3 中,我无法减去稀疏数据帧的均值列。我试过了:

df_norm= df.sub(df.mean(axis=1), axis=0)

但我得到:

AttributeError: module 'pandas._libs.sparse' has no attribute 'sparse_sub_float32'

如果您使用较旧的 Pandas SparseDataFrame 结构,您可能会遇到此错误。然而,在最新的 Pandas(我使用 0.25.3)中,有一种不同的方法来处理稀疏问题,你的代码工作正常。考虑将您的数据框转换为现代稀疏类型。参见 https://pandas.pydata.org/pandas-docs/stable/user_guide/sparse.html#sparse-migration。 下面是一个工作示例

df = pd.DataFrame (np.random.randint(0,100,(5,5)))
dtype = pd.SparseDtype(int, fill_value=0)   # define sparse type
df = df.astype(dtype)  # to new sparse type
print(df.sub(df.mean(axis=1), axis=0))

      0     1     2     3     4
0 -28.6  43.4 -42.6 -14.6  42.4
1  29.4  25.4 -48.6  -4.6  -1.6
2 -12.4  52.6 -15.4 -17.4  -7.4
3 -20.8  -2.8  10.2  -6.8  20.2
4  35.8  -4.2  19.8 -16.2 -35.2