scipy.sparse.

safely_cast_index_arrays#

scipy.sparse.safely_cast_index_arrays(A, idx_dtype=<class 'numpy.int32'>, msg='')[原始碼]#

安全地將稀疏陣列索引轉換為 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 或 ndarrays 的元組

根據 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')