scipy.sparse.
safely_cast_index_arrays#
- scipy.sparse.safely_cast_index_arrays(A, idx_dtype=<class 'numpy.int32'>, msg='')[source]#
安全地将稀疏数组索引转换为 idx_dtype。
检查 A 的形状以确定是否可以安全地将其索引数组转换为 dtype idx_dtype。如果形状中的任何维度大于 dtype 所能容纳的范围,则转换不安全,因此会引发
ValueError
。如果安全,则将索引数组转换为 idx_dtype 并返回结果,而不更改输入 A。调用者可以根据需要将结果赋值给 A 的属性,或者直接使用重新转换后的索引数组。除非需要向下转换,否则将返回原始索引数组。您可以测试例如
A.indptr is new_indptr
以查看是否发生了向下转换。在版本 1.15.0 中添加。
- 参数:
- A稀疏数组或矩阵
应向下转换索引数组的数组。
- idx_dtypedtype
期望的 dtype。应为整数 dtype(默认值:
np.int32
)。scipy.sparse 大部分使用 int64 或 int32。- msg字符串,可选
如果数组形状太大而无法适应 idx_dtype,则添加到 ValueError 消息末尾的字符串。错误消息为
f"<index> values too large for {msg}"
它应指明为什么需要向下转换,例如“SuperLU”,默认值为 f”dtype {idx_dtype}”。
- 返回:
- idx_arraysndarray 或 ndarray 元组
根据
A.format
,索引数组在转换为 idx_dtype 后返回。对于 CSC/CSR,返回(indices, indptr)
。对于 COO,返回coords
。对于 DIA,返回offsets
。对于 BSR,返回(indices, indptr)
。
- 引发:
- ValueError
如果数组的形状不适合新的 dtype,或者稀疏格式不使用索引数组。
示例
>>> import numpy as np >>> from scipy import sparse >>> data = [3] >>> coords = (np.array([3]), np.array([1])) # Note: int64 arrays >>> A = sparse.coo_array((data, coords)) >>> A.coords[0].dtype dtype('int64')
>>> # rescast after construction, raising exception if shape too big >>> coords = sparse.safely_cast_index_arrays(A, np.int32) >>> A.coords[0] is coords[0] # False if casting is needed False >>> A.coords = coords # set the index dtype of A >>> A.coords[0].dtype dtype('int32')