egttools.analytical.sed_analytical.csr_matrix

class csr_matrix(arg1, shape=None, dtype=None, copy=False, *, maxprint=None)[source]

Bases: spmatrix, _csr_base

Compressed Sparse Row matrix.

This can be instantiated in several ways:
csr_matrix(D)

where D is a 2-D ndarray

csr_matrix(S)

with another sparse array or matrix S (equivalent to S.tocsr())

csr_matrix((M, N), [dtype])

to construct an empty matrix with shape (M, N) dtype is optional, defaulting to dtype=’d’.

csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])

where data, row_ind and col_ind satisfy the relationship a[row_ind[k], col_ind[k]] = data[k].

csr_matrix((data, indices, indptr), [shape=(M, N)])

is the standard CSR representation where the column indices for row i are stored in indices[indptr[i]:indptr[i+1]] and their corresponding values are stored in data[indptr[i]:indptr[i+1]]. If the shape parameter is not supplied, the matrix dimensions are inferred from the index arrays.

dtype

Data type of the matrix

Type:

dtype

shape

Shape of the matrix

Type:

2-tuple

ndim

Number of dimensions (this is always 2)

Type:

int

nnz
size
data

CSR format data array of the matrix

indices

CSR format index array of the matrix

indptr

CSR format index pointer array of the matrix

has_sorted_indices
has_canonical_format
T

Notes

Sparse matrices can be used in arithmetic operations: they support addition, subtraction, multiplication, division, and matrix power.

Advantages of the CSR format
  • efficient arithmetic operations CSR + CSR, CSR * CSR, etc.

  • efficient row slicing

  • fast matrix vector products

Disadvantages of the CSR format
  • slow column slicing operations (consider CSC)

  • changes to the sparsity structure are expensive (consider LIL or DOK)

Canonical Format
  • Within each row, indices are sorted by column.

  • There are no duplicate entries.

Examples

>>> import numpy as np
>>> from scipy.sparse import csr_matrix
>>> csr_matrix((3, 4), dtype=np.int8).toarray()
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]], dtype=int8)
>>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])
>>> indptr = np.array([0, 2, 3, 6])
>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])

Duplicate entries are summed together:

>>> row = np.array([0, 1, 2, 0])
>>> col = np.array([0, 1, 1, 0])
>>> data = np.array([1, 2, 4, 8])
>>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
array([[9, 0, 0],
       [0, 2, 0],
       [0, 4, 0]])

As an example of how to construct a CSR matrix incrementally, the following snippet builds a term-document matrix from texts:

>>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
>>> indptr = [0]
>>> indices = []
>>> data = []
>>> vocabulary = {}
>>> for d in docs:
...     for term in d:
...         index = vocabulary.setdefault(term, len(vocabulary))
...         indices.append(index)
...         data.append(1)
...     indptr.append(len(indices))
...
>>> csr_matrix((data, indices, indptr), dtype=int).toarray()
array([[2, 1, 0, 0],
       [0, 1, 1, 1]])

Methods

arcsin

Element-wise arcsin.

arcsinh

Element-wise arcsinh.

arctan

Element-wise arctan.

arctanh

Element-wise arctanh.

argmax

Return indices of maximum elements along an axis.

argmin

Return indices of minimum elements along an axis.

asformat

Return this array/matrix in the passed format.

asfptype

Upcast matrix to a floating point format (if necessary)

astype

Cast the array/matrix elements to a specified type.

ceil

Element-wise ceil.

check_format

Check whether the array/matrix respects the CSR or CSC format.

conj

Element-wise complex conjugation.

conjugate

Element-wise complex conjugation.

copy

Returns a copy of this array/matrix.

count_nonzero

Number of non-zero entries, equivalent to

deg2rad

Element-wise deg2rad.

diagonal

Returns the kth diagonal of the array/matrix.

dot

Ordinary dot product

eliminate_zeros

Remove zero entries from the array/matrix

expm1

Element-wise expm1.

floor

Element-wise floor.

getH

Return the Hermitian transpose of this matrix.

get_shape

Get the shape of the matrix

getcol

Returns a copy of column j of the matrix, as an (m x 1) sparse matrix (column vector).

getformat

Matrix storage format

getmaxprint

Maximum number of elements to display when printed.

getnnz

Number of stored values, including explicit zeros.

getrow

Returns a copy of row i of the matrix, as a (1 x n) sparse matrix (row vector).

log1p

Element-wise log1p.

max

Return the maximum of the array/matrix or maximum along an axis.

maximum

Element-wise maximum between this and another array/matrix.

mean

Compute the arithmetic mean along the specified axis.

min

Return the minimum of the array/matrix or maximum along an axis.

minimum

Element-wise minimum between this and another array/matrix.

multiply

Point-wise multiplication by array/matrix, vector, or scalar.

nanmax

Return the maximum, ignoring any Nans, along an axis.

nanmin

Return the minimum, ignoring any Nans, along an axis.

nonzero

Nonzero indices of the array/matrix.

power

This function performs element-wise power.

prune

Remove empty space after all non-zero elements.

rad2deg

Element-wise rad2deg.

reshape

Gives a new shape to a sparse array/matrix without changing its data.

resize

Resize the array/matrix in-place to dimensions given by shape

rint

Element-wise rint.

set_shape

Set the shape of the matrix in-place

setdiag

Set diagonal or off-diagonal elements of the array/matrix.

sign

Element-wise sign.

sin

Element-wise sin.

sinh

Element-wise sinh.

sort_indices

Sort the indices of this array/matrix in place

sorted_indices

Return a copy of this array/matrix with sorted indices

sqrt

Element-wise sqrt.

sum

Sum the array/matrix elements over a given axis.

sum_duplicates

Eliminate duplicate entries by adding them together

tan

Element-wise tan.

tanh

Element-wise tanh.

toarray

Return a dense ndarray representation of this sparse array/matrix.

tobsr

Convert this array/matrix to Block Sparse Row format.

tocoo

Convert this array/matrix to COOrdinate format.

tocsc

Convert this array/matrix to Compressed Sparse Column format.

tocsr

Convert this array/matrix to Compressed Sparse Row format.

todense

Return a dense representation of this sparse matrix.

todia

Convert this array/matrix to sparse DIAgonal format.

todok

Convert this array/matrix to Dictionary Of Keys format.

tolil

Convert this array/matrix to List of Lists format.

trace

Returns the sum along diagonals of the sparse array/matrix.

transpose

Reverses the dimensions of the sparse array/matrix.

trunc

Element-wise trunc.

Attributes

T

Transpose.

dtype

format

Format string for matrix.

has_canonical_format

Whether the array/matrix has sorted indices and no duplicates

has_sorted_indices

Whether the indices are sorted

imag

ndim

nnz

Number of stored values, including explicit zeros.

real

shape

Shape of the matrix

size

Number of stored values.

__abs__()
__add__(other)
__bool__()
__div__(other)
__eq__(other)

Return self==value.

__ge__(other)

Return self>=value.

__getitem__(key)
__gt__(other)

Return self>value.

__iadd__(other)
__idiv__(other)
__imul__(other)
__init__(arg1, shape=None, dtype=None, copy=False, *, maxprint=None)
__isub__(other)
__iter__()
__itruediv__(other)
__le__(other)

Return self<=value.

__len__()
__lt__(other)

Return self<value.

__matmul__(other)
__mul__(other)
__ne__(other)

Return self!=value.

__neg__()
__nonzero__()
__pow__(power)
__radd__(other)
__rdiv__(other)
__repr__()

Return repr(self).

__rmatmul__(other)
__rmul__(other)
__round__(ndigits=0)
__rsub__(other)
__rtruediv__(other)
__setitem__(key, x)
__str__()

Return str(self).

__sub__(other)
__truediv__(other)
arcsin()

Element-wise arcsin.

See numpy.arcsin for more information.

arcsinh()

Element-wise arcsinh.

See numpy.arcsinh for more information.

arctan()

Element-wise arctan.

See numpy.arctan for more information.

arctanh()

Element-wise arctanh.

See numpy.arctanh for more information.

argmax(axis=None, out=None, *, explicit=False)

Return indices of maximum elements along an axis.

By default, implicit zero elements are taken into account. If there are several minimum values, the index of the first occurrence is returned. If explicit is set, only explicitly stored elements will be considered.

Parameters:
  • axis ({-2, -1, 0, 1, None}, optional) – Axis along which the argmax is computed. If None (default), index of the maximum element in the flatten data is returned.

  • out (None, optional) – This argument is in the signature solely for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used.

  • explicit ({False, True} optional (default: False)) –

    When set to True, only explicitly stored elements will be considered. If axis is not None and a row/column has no stored elements, argmax is undefined, so the index 0 is returned for that row/column.

    Added in version 1.15.0.

Returns:

ind – Indices of maximum elements. If matrix, its size along axis is 1.

Return type:

numpy.matrix or int

argmin(axis=None, out=None, *, explicit=False)

Return indices of minimum elements along an axis.

By default, implicit zero elements are taken into account. If there are several minimum values, the index of the first occurrence is returned. If explicit is set, only explicitly stored elements will be considered.

Parameters:
  • axis ({-2, -1, 0, 1, None}, optional) – Axis along which the argmin is computed. If None (default), index of the minimum element in the flatten data is returned.

  • out (None, optional) – This argument is in the signature solely for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used.

  • explicit ({False, True} optional (default: False)) –

    When set to True, only explicitly stored elements will be considered. If axis is not None and a row/column has no stored elements, argmin is undefined, so the index 0 is returned for that row/column.

    Added in version 1.15.0.

Returns:

indnumpy.matrix or int

Indices of minimum elements. If matrix, its size along axis is 1.

asformat(format, copy=False)

Return this array/matrix in the passed format.

Parameters:
  • format ({str, None}) – The desired sparse format (“csr”, “csc”, “lil”, “dok”, “array”, …) or None for no conversion.

  • copy (bool, optional) – If True, the result is guaranteed to not share data with self.

Returns:

A

Return type:

This array/matrix in the passed format.

asfptype()

Upcast matrix to a floating point format (if necessary)

astype(dtype, casting='unsafe', copy=True)

Cast the array/matrix elements to a specified type.

Parameters:
  • dtype (string or numpy dtype) – Typecode or data-type to which to cast the data.

  • casting ({'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional) – Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility. ‘no’ means the data types should not be cast at all. ‘equiv’ means only byte-order changes are allowed. ‘safe’ means only casts which can preserve values are allowed. ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done.

  • copy (bool, optional) – If copy is False, the result might share some memory with this array/matrix. If copy is True, it is guaranteed that the result and this array/matrix do not share any memory.

ceil()

Element-wise ceil.

See numpy.ceil for more information.

check_format(full_check=True)

Check whether the array/matrix respects the CSR or CSC format.

Parameters:

full_check (bool, optional) – If True, run rigorous check, scanning arrays for valid values. Note that activating those check might copy arrays for casting, modifying indices and index pointers’ inplace. If False, run basic checks on attributes. O(1) operations. Default is True.

conj(copy=True)

Element-wise complex conjugation.

If the array/matrix is of non-complex data type and copy is False, this method does nothing and the data is not copied.

Parameters:

copy (bool, optional) – If True, the result is guaranteed to not share data with self.

Returns:

A

Return type:

The element-wise complex conjugate.

conjugate(copy=True)

Element-wise complex conjugation.

If the array/matrix is of non-complex data type and copy is False, this method does nothing and the data is not copied.

Parameters:

copy (bool, optional) – If True, the result is guaranteed to not share data with self.

Returns:

A

Return type:

The element-wise complex conjugate.

copy()

Returns a copy of this array/matrix.

No data/indices will be shared between the returned value and current array/matrix.

count_nonzero(axis=None)

Number of non-zero entries, equivalent to

np.count_nonzero(a.toarray(), axis=axis)

Unlike the nnz property, which return the number of stored entries (the length of the data attribute), this method counts the actual number of non-zero entries in data.

Duplicate entries are summed before counting.

Parameters:

axis ({-2, -1, 0, 1, None} optional) –

Count nonzeros for the whole array, or along a specified axis.

Added in version 1.15.0.

Returns:

A reduced array (no axis axis) holding the number of nonzero values for each of the indices of the nonaxis dimensions.

Return type:

numpy array

Notes

If you want to count nonzero and explicit zero stored values (e.g. nnz) along an axis, two fast idioms are provided by numpy functions for the common CSR, CSC, COO formats.

For the major axis in CSR (rows) and CSC (cols) use np.diff:

>>> import numpy as np
>>> import scipy as sp
>>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]])
>>> major_axis_stored_values = np.diff(A.indptr)  # -> np.array([2, 1])

For the minor axis in CSR (cols) and CSC (rows) use numpy.bincount with minlength A.shape[1] for CSR and A.shape[0] for CSC:

>>> csr_minor_stored_values = np.bincount(A.indices, minlength=A.shape[1])

For COO, use the minor axis approach for either axis:

>>> A = A.tocoo()
>>> coo_axis0_stored_values = np.bincount(A.coords[0], minlength=A.shape[1])
>>> coo_axis1_stored_values = np.bincount(A.coords[1], minlength=A.shape[0])

Examples

>>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]])
>>> A.count_nonzero(axis=0)
array([2, 1, 0])
deg2rad()

Element-wise deg2rad.

See numpy.deg2rad for more information.

diagonal(k=0)

Returns the kth diagonal of the array/matrix.

Parameters:

k (int, optional) –

Which diagonal to get, corresponding to elements a[i, i+k]. Default: 0 (the main diagonal).

Added in version 1.0.

See also

numpy.diagonal

Equivalent numpy function.

Examples

>>> from scipy.sparse import csr_array
>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
>>> A.diagonal()
array([1, 0, 5])
>>> A.diagonal(k=1)
array([2, 3])
dot(other)

Ordinary dot product

Examples

>>> import numpy as np
>>> from scipy.sparse import csr_array
>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
>>> v = np.array([1, 0, -1])
>>> A.dot(v)
array([ 1, -3, -1], dtype=int64)
eliminate_zeros()

Remove zero entries from the array/matrix

This is an in place operation.

expm1()

Element-wise expm1.

See numpy.expm1 for more information.

floor()

Element-wise floor.

See numpy.floor for more information.

getH()

Return the Hermitian transpose of this matrix.

See also

numpy.matrix.getH

NumPy’s implementation of getH for matrices

get_shape()

Get the shape of the matrix

getcol(j)

Returns a copy of column j of the matrix, as an (m x 1) sparse matrix (column vector).

getformat()

Matrix storage format

getmaxprint()

Maximum number of elements to display when printed.

getnnz(axis=None)

Number of stored values, including explicit zeros.

Parameters:

axis (None, 0, or 1) – Select between the number of values across the whole array, in each column, or in each row.

getrow(i)

Returns a copy of row i of the matrix, as a (1 x n) sparse matrix (row vector).

log1p()

Element-wise log1p.

See numpy.log1p for more information.

max(axis=None, out=None, *, explicit=False)

Return the maximum of the array/matrix or maximum along an axis.

By default, all elements are taken into account, not just the non-zero ones. But with explicit set, only the stored elements are considered.

Parameters:
  • axis ({-2, -1, 0, 1, None} optional) – Axis along which the sum is computed. The default is to compute the maximum over all elements, returning a scalar (i.e., axis = None).

  • out (None, optional) – This argument is in the signature solely for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used.

  • explicit ({False, True} optional (default: False)) –

    When set to True, only the stored elements will be considered. If a row/column is empty, the sparse.coo_array returned has no stored element (i.e. an implicit zero) for that row/column.

    Added in version 1.15.0.

Returns:

amax – Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is a sparse.coo_array of dimension a.ndim - 1.

Return type:

coo_array or scalar

See also

min

The minimum value of a sparse array/matrix along a given axis.

numpy.max

NumPy’s implementation of ‘max’

maximum(other)

Element-wise maximum between this and another array/matrix.

mean(axis=None, dtype=None, out=None)

Compute the arithmetic mean along the specified axis.

Returns the average of the array/matrix elements. The average is taken over all elements in the array/matrix by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

Parameters:
  • axis ({-2, -1, 0, 1, None} optional) – Axis along which the mean is computed. The default is to compute the mean of all elements in the array/matrix (i.e., axis = None).

  • dtype (data-type, optional) –

    Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.

    Added in version 0.18.0.

  • out (np.matrix, optional) –

    Alternative output matrix in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.

    Added in version 0.18.0.

Returns:

m

Return type:

np.matrix

See also

numpy.matrix.mean

NumPy’s implementation of ‘mean’ for matrices

min(axis=None, out=None, *, explicit=False)

Return the minimum of the array/matrix or maximum along an axis.

By default, all elements are taken into account, not just the non-zero ones. But with explicit set, only the stored elements are considered.

Parameters:
  • axis ({-2, -1, 0, 1, None} optional) – Axis along which the sum is computed. The default is to compute the minimum over all elements, returning a scalar (i.e., axis = None).

  • out (None, optional) – This argument is in the signature solely for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used.

  • explicit ({False, True} optional (default: False)) –

    When set to True, only the stored elements will be considered. If a row/column is empty, the sparse.coo_array returned has no stored element (i.e. an implicit zero) for that row/column.

    Added in version 1.15.0.

Returns:

amin – Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is a sparse.coo_array of dimension a.ndim - 1.

Return type:

coo_matrix or scalar

See also

max

The maximum value of a sparse array/matrix along a given axis.

numpy.min

NumPy’s implementation of ‘min’

minimum(other)

Element-wise minimum between this and another array/matrix.

multiply(other)

Point-wise multiplication by array/matrix, vector, or scalar.

nanmax(axis=None, out=None, *, explicit=False)

Return the maximum, ignoring any Nans, along an axis.

Return the maximum, ignoring any Nans, of the array/matrix along an axis. By default this takes all elements into account, but with explicit set, only stored elements are considered.

Added in version 1.11.0.

Parameters:
  • axis ({-2, -1, 0, 1, None} optional) – Axis along which the maximum is computed. The default is to compute the maximum over all elements, returning a scalar (i.e., axis = None).

  • out (None, optional) – This argument is in the signature solely for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used.

  • explicit ({False, True} optional (default: False)) –

    When set to True, only the stored elements will be considered. If a row/column is empty, the sparse.coo_array returned has no stored element (i.e. an implicit zero) for that row/column.

    Added in version 1.15.0.

Returns:

amax – Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is a sparse.coo_array of dimension a.ndim - 1.

Return type:

coo_array or scalar

See also

nanmin

The minimum value of a sparse array/matrix along a given axis, ignoring NaNs.

max

The maximum value of a sparse array/matrix along a given axis, propagating NaNs.

numpy.nanmax

NumPy’s implementation of ‘nanmax’.

nanmin(axis=None, out=None, *, explicit=False)

Return the minimum, ignoring any Nans, along an axis.

Return the minimum, ignoring any Nans, of the array/matrix along an axis. By default this takes all elements into account, but with explicit set, only stored elements are considered.

Added in version 1.11.0.

Parameters:
  • axis ({-2, -1, 0, 1, None} optional) – Axis along which the minimum is computed. The default is to compute the minimum over all elements, returning a scalar (i.e., axis = None).

  • out (None, optional) – This argument is in the signature solely for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used.

  • explicit ({False, True} optional (default: False)) –

    When set to True, only the stored elements will be considered. If a row/column is empty, the sparse.coo_array returned has no stored element (i.e. an implicit zero) for that row/column.

    Added in version 1.15.0.

Returns:

amin – Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is a sparse.coo_array of dimension a.ndim - 1.

Return type:

coo_array or scalar

See also

nanmax

The maximum value of a sparse array/matrix along a given axis, ignoring NaNs.

min

The minimum value of a sparse array/matrix along a given axis, propagating NaNs.

numpy.nanmin

NumPy’s implementation of ‘nanmin’.

nonzero()

Nonzero indices of the array/matrix.

Returns a tuple of arrays (row,col) containing the indices of the non-zero elements of the array.

Examples

>>> from scipy.sparse import csr_array
>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
>>> A.nonzero()
(array([0, 0, 1, 2, 2], dtype=int32), array([0, 1, 2, 0, 2], dtype=int32))
power(n, dtype=None)

This function performs element-wise power.

Parameters:
  • n (scalar) – n is a non-zero scalar (nonzero avoids dense ones creation) If zero power is desired, special case it to use np.ones

  • dtype (If dtype is not specified, the current dtype will be preserved.)

:raises NotImplementedError : if n is a zero scalar: If zero power is desired, special case it to use np.ones(A.shape, dtype=A.dtype)

prune()

Remove empty space after all non-zero elements.

rad2deg()

Element-wise rad2deg.

See numpy.rad2deg for more information.

reshape(self, shape, order='C', copy=False)

Gives a new shape to a sparse array/matrix without changing its data.

Parameters:
  • shape (length-2 tuple of ints) – The new shape should be compatible with the original shape.

  • order ({'C', 'F'}, optional) – Read the elements using this index order. ‘C’ means to read and write the elements using C-like index order; e.g., read entire first row, then second row, etc. ‘F’ means to read and write the elements using Fortran-like index order; e.g., read entire first column, then second column, etc.

  • copy (bool, optional) – Indicates whether or not attributes of self should be copied whenever possible. The degree to which attributes are copied varies depending on the type of sparse array being used.

Returns:

reshaped – A sparse array/matrix with the given shape, not necessarily of the same format as the current object.

Return type:

sparse array/matrix

See also

numpy.reshape

NumPy’s implementation of ‘reshape’ for ndarrays

resize(*shape)

Resize the array/matrix in-place to dimensions given by shape

Any elements that lie within the new shape will remain at the same indices, while non-zero elements lying outside the new shape are removed.

Parameters:

shape ((int, int)) – number of rows and columns in the new array/matrix

Notes

The semantics are not identical to numpy.ndarray.resize or numpy.resize. Here, the same data will be maintained at each index before and after reshape, if that index is within the new bounds. In numpy, resizing maintains contiguity of the array, moving elements around in the logical array but not within a flattened representation.

We give no guarantees about whether the underlying data attributes (arrays, etc.) will be modified in place or replaced with new objects.

rint()

Element-wise rint.

See numpy.rint for more information.

set_shape(shape)

Set the shape of the matrix in-place

setdiag(values, k=0)

Set diagonal or off-diagonal elements of the array/matrix.

Parameters:
  • values (array_like) –

    New values of the diagonal elements.

    Values may have any length. If the diagonal is longer than values, then the remaining diagonal entries will not be set. If values are longer than the diagonal, then the remaining values are ignored.

    If a scalar value is given, all of the diagonal is set to it.

  • k (int, optional) – Which off-diagonal to set, corresponding to elements a[i,i+k]. Default: 0 (the main diagonal).

sign()

Element-wise sign.

See numpy.sign for more information.

sin()

Element-wise sin.

See numpy.sin for more information.

sinh()

Element-wise sinh.

See numpy.sinh for more information.

sort_indices()

Sort the indices of this array/matrix in place

sorted_indices()

Return a copy of this array/matrix with sorted indices

sqrt()

Element-wise sqrt.

See numpy.sqrt for more information.

sum(axis=None, dtype=None, out=None)

Sum the array/matrix elements over a given axis.

Parameters:
  • axis ({-2, -1, 0, 1, None} optional) – Axis along which the sum is computed. The default is to compute the sum of all the array/matrix elements, returning a scalar (i.e., axis = None).

  • dtype (dtype, optional) –

    The type of the returned array/matrix and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

    Added in version 0.18.0.

  • out (np.matrix, optional) –

    Alternative output matrix in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.

    Added in version 0.18.0.

Returns:

sum_along_axis – A matrix with the same shape as self, with the specified axis removed.

Return type:

np.matrix

See also

numpy.matrix.sum

NumPy’s implementation of ‘sum’ for matrices

sum_duplicates()

Eliminate duplicate entries by adding them together

This is an in place operation.

tan()

Element-wise tan.

See numpy.tan for more information.

tanh()

Element-wise tanh.

See numpy.tanh for more information.

toarray(order=None, out=None)

Return a dense ndarray representation of this sparse array/matrix.

Parameters:
  • order ({'C', 'F'}, optional) – Whether to store multidimensional data in C (row-major) or Fortran (column-major) order in memory. The default is ‘None’, which provides no ordering guarantees. Cannot be specified in conjunction with the out argument.

  • out (ndarray, 2-D, optional) – If specified, uses this array as the output buffer instead of allocating a new array to return. The provided array must have the same shape and dtype as the sparse array/matrix on which you are calling the method. For most sparse types, out is required to be memory contiguous (either C or Fortran ordered).

Returns:

arr – An array with the same shape and containing the same data represented by the sparse array/matrix, with the requested memory order. If out was passed, the same object is returned after being modified in-place to contain the appropriate values.

Return type:

ndarray, 2-D

tobsr(blocksize=None, copy=True)

Convert this array/matrix to Block Sparse Row format.

With copy=False, the data/indices may be shared between this array/matrix and the resultant bsr_array/matrix.

When blocksize=(R, C) is provided, it will be used for construction of the bsr_array/matrix.

tocoo(copy=True)

Convert this array/matrix to COOrdinate format.

With copy=False, the data/indices may be shared between this array/matrix and the resultant coo_array/matrix.

tocsc(copy=False)

Convert this array/matrix to Compressed Sparse Column format.

With copy=False, the data/indices may be shared between this array/matrix and the resultant csc_array/matrix.

tocsr(copy=False)

Convert this array/matrix to Compressed Sparse Row format.

With copy=False, the data/indices may be shared between this array/matrix and the resultant csr_array/matrix.

todense(order=None, out=None)

Return a dense representation of this sparse matrix.

Parameters:
  • order ({'C', 'F'}, optional) – Whether to store multi-dimensional data in C (row-major) or Fortran (column-major) order in memory. The default is ‘None’, which provides no ordering guarantees. Cannot be specified in conjunction with the out argument.

  • out (ndarray, 2-D, optional) – If specified, uses this array (or numpy.matrix) as the output buffer instead of allocating a new array to return. The provided array must have the same shape and dtype as the sparse matrix on which you are calling the method.

Returns:

arr – A NumPy matrix object with the same shape and containing the same data represented by the sparse matrix, with the requested memory order. If out was passed and was an array (rather than a numpy.matrix), it will be filled with the appropriate values and returned wrapped in a numpy.matrix object that shares the same memory.

Return type:

numpy.matrix, 2-D

todia(copy=False)

Convert this array/matrix to sparse DIAgonal format.

With copy=False, the data/indices may be shared between this array/matrix and the resultant dia_array/matrix.

todok(copy=False)

Convert this array/matrix to Dictionary Of Keys format.

With copy=False, the data/indices may be shared between this array/matrix and the resultant dok_array/matrix.

tolil(copy=False)

Convert this array/matrix to List of Lists format.

With copy=False, the data/indices may be shared between this array/matrix and the resultant lil_array/matrix.

trace(offset=0)

Returns the sum along diagonals of the sparse array/matrix.

Parameters:

offset (int, optional) – Which diagonal to get, corresponding to elements a[i, i+offset]. Default: 0 (the main diagonal).

transpose(axes=None, copy=False)

Reverses the dimensions of the sparse array/matrix.

Parameters:
  • axes (None, optional) – This argument is in the signature solely for NumPy compatibility reasons. Do not pass in anything except for the default value.

  • copy (bool, optional) – Indicates whether or not attributes of self should be copied whenever possible. The degree to which attributes are copied varies depending on the type of sparse array/matrix being used.

Returns:

p

Return type:

self with the dimensions reversed.

Notes

If self is a csr_array or a csc_array, then this will return a csc_array or a csr_array, respectively.

See also

numpy.transpose

NumPy’s implementation of ‘transpose’ for ndarrays

trunc()

Element-wise trunc.

See numpy.trunc for more information.

property T

Transpose.

__annotations__ = {}
__array_priority__ = 10.1
__hash__ = None
property dtype
property format: str

Format string for matrix.

property has_canonical_format: bool

Whether the array/matrix has sorted indices and no duplicates

Returns
  • True: if the above applies

  • False: otherwise

has_canonical_format implies has_sorted_indices, so if the latter flag is False, so will the former be; if the former is found True, the latter flag is also set.

property has_sorted_indices: bool

Whether the indices are sorted

Returns
  • True: if the indices of the array/matrix are in sorted order

  • False: otherwise

property imag
property ndim: int
property nnz: int

Number of stored values, including explicit zeros.

See also

count_nonzero

Number of non-zero entries

property real
property shape

Shape of the matrix

property size: int

Number of stored values.

See also

count_nonzero

Number of non-zero values.