DOK

class sparse.DOK(shape, data=None, dtype=None, fill_value=None)[source]

A class for building sparse multidimensional arrays.

Parameters
  • shape (tuple[int] (DOK.ndim,)) – The shape of the array.

  • 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 None if no elements have been set yet.

Type

numpy.dtype

shape

The shape of this array.

Type

tuple[int]

data

The keys of this dictionary contain all the indices and the values contain the nonzero entries.

Type

dict

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, 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 DOK arrays to COO arrays, or numpy.ndarray objects.

>>> from sparse import COO
>>> s3 = COO(s2)
>>> s3
<COO: shape=(5, 5), dtype=int64, nnz=4, fill_value=0>
>>> s2.todense()  # doctest: +NORMALIZE_WHITESPACE
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 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, fill_value=0.0>

Attributes

DOK.density

The ratio of nonzero to all elements in this array.

DOK.ndim

The number of dimensions of this array.

DOK.nnz

The number of nonzero elements in this array.

DOK.size

The number of all elements (including zeros) in this array.

Methods

DOK.asformat(format)

Convert this sparse array to a given format.

DOK.from_coo(x)

Get a DOK array from a COO array.

DOK.from_numpy(x)

Get a DOK array from a Numpy array.

DOK.to_coo()

Convert this DOK array to a COO array.

DOK.todense()

Convert this DOK array into a Numpy array.