Constructing COO
arrays¶
From coordinates and data¶
This is the preferred way of constructing COO
arrays. The
constructor for COO
(see COO.__init__
) can create these
objects from two main variables: coords
and data
.
coords
contains the indices where the data is nonzero, and
data
contains the data corresponding to those indices. For
example, the following code will generate a \(5 \times 5\)
identity matrix:
coords = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
data = [1, 1, 1, 1, 1]
s = COO(coords, data)
In general coords
should be a (ndim, nnz)
shaped
array. Each row of coords
contains one dimension of the
desired sparse array, and each column contains the index
corresponding to that nonzero element. data
contains
the nonzero elements of the array corresponding to the indices
in coords
. Its shape should be (nnz,)
You can, and should, pass in numpy.ndarray
objects for
coords
and data
.
In this case, the shape of the resulting array was determined from
the maximum index in each dimension. If the array extends beyond
the maximum index in coords
, you should supply a shape
explicitly. For example, if we did the following without the
shape
keyword argument, it would result in a
\(4 \times 5\) matrix, but maybe we wanted one that was actually
\(5 \times 5\).
coords = [[0, 3, 2, 1], [4, 1, 2, 0]]
data = [1, 4, 2, 1]
s = COO(coords, data, shape=(5, 5))
From scipy.sparse.spmatrix
objects¶
To construct COO
array from scipy.sparse.spmatrix
objects, you can use the COO.from_scipy_sparse
method. As an
example, if x
is a scipy.sparse.spmatrix
, you can
do the following to get an equivalent COO
array:
s = COO.from_scipy_sparse(x)
From numpy.ndarray
objects¶
To construct COO
arrays from numpy.ndarray
objects, you can use the COO.from_numpy
method. As an
example, if x
is a numpy.ndarray
, you can
do the following to get an equivalent COO
array:
s = COO.from_numpy(x)
Generating random COO
objects¶
The sparse.random
method can be used to create random
COO
arrays. For example, the following will generate
a \(10 \times 10\) matrix with \(10\) nonzero entries,
each in the interval \([0, 1)\).
s = sparse.random((10, 10), density=0.1)