DOK
- class sparse.DOK(shape, data=None, dtype=None, fill_value=None)[source]
A class for building sparse multidimensional arrays.
- Parameters:
data (dict, optional) – The key-value pairs for the data in this array.
dtype (np.dtype, optional) – The data type of this array. If left empty, it is inferred from the first element.
fill_value (scalar, optional) – The fill value of this array.
- dtype
The datatype of this array. Can be
Noneif no elements have been set yet.- Type:
- data
The keys of this dictionary contain all the indices and the values contain the nonzero entries.
- Type:
See also
COOA read-only sparse array.
Examples
You can create
DOKobjects 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, fill_value=0>
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, fill_value=0>
You can convert
DOKarrays toCOOarrays, ornumpy.ndarrayobjects.>>> from sparse import COO >>> s3 = COO(s2) >>> s3 <COO: shape=(5, 5), dtype=int64, nnz=4, fill_value=0> >>> 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, fill_value=0> >>> s5 = DOK.from_coo(s4) >>> s5 <DOK: shape=(4, 4), dtype=uint8, nnz=4, fill_value=0>
You can also create
DOKarrays 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, fill_value=0.0>
Attributes
The ratio of nonzero to all elements in this array.
The number of dimensions of this array.
The number of nonzero elements in this array.
The number of all elements (including zeros) in this array.
Methods
DOK.asformat(format, **kwargs)Convert this sparse array to a given format.
DOK.from_coo(x)Get a
DOKarray from a Numpy array.Create a
DOKarray from ascipy.sparse.spmatrix.Convert this
DOKarray into a Numpy array.