DOK¶
-
class
sparse.
DOK
(shape, data=None, dtype=None)[source]¶ A class for building sparse multidimensional arrays.
Parameters: -
dtype
¶ numpy.dtype – The datatype of this array. Can be
None
if no elements have been set yet.
-
shape
¶ tuple[int] – The shape of this array.
-
data
¶ dict – The keys of this dictionary contain all the indices and the values contain the nonzero entries.
See also
COO
- A read-only sparse array.
Examples
You can create
DOK
objects from Numpy arrays.>>> x = np.eye(5, dtype=np.uint8) >>> x[2, 3] = 5 >>> s = DOK.from_numpy(x) >>> s <DOK: shape=(5, 5), dtype=uint8, nnz=6>
You can also create them from just shapes, and use slicing assignment.
>>> s2 = DOK((5, 5), dtype=np.int64) >>> s2[1:3, 1:3] = [[4, 5], [6, 7]] >>> s2 <DOK: shape=(5, 5), dtype=int64, nnz=4>
You can convert
DOK
arrays toCOO
arrays, ornumpy.ndarray
objects.>>> from sparse import COO >>> s3 = COO(s2) >>> s3 <COO: shape=(5, 5), dtype=int64, nnz=4, sorted=False, duplicates=False> >>> s2.todense() array([[0, 0, 0, 0, 0], [0, 4, 5, 0, 0], [0, 6, 7, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
>>> s4 = COO.from_numpy(np.eye(4, dtype=np.uint8)) >>> s4 <COO: shape=(4, 4), dtype=uint8, nnz=4, sorted=True, duplicates=False> >>> s5 = DOK.from_coo(s4) >>> s5 <DOK: shape=(4, 4), dtype=uint8, nnz=4>
You can also create
DOK
arrays from a shape and a dict of values. Zeros are automatically ignored.>>> values = { ... (1, 2, 3): 4, ... (3, 2, 1): 0, ... } >>> s6 = DOK((5, 5, 5), values) >>> s6 <DOK: shape=(5, 5, 5), dtype=int64, nnz=1>
Attributes
DOK.ndim
The number of dimensions in this array. DOK.nnz
The number of nonzero elements in this array. Methods
DOK.from_coo
(x)Get a DOK
array from aCOO
array.DOK.from_numpy
(x)Get a DOK
array from a Numpy array.DOK.to_coo
()Convert this DOK
array to aCOO
array.DOK.todense
()Convert this DOK
array into a Numpy array.-