egttools.utils.csc_matrix

class csc_matrix(arg1, shape=None, dtype=None, copy=False)[source]

Bases: _cs_matrix

Compressed Sparse Column matrix

This can be instantiated in several ways:

csc_matrix(D)

with a dense matrix or rank-2 ndarray D

csc_matrix(S)

with another sparse matrix S (equivalent to S.tocsc())

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

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

csc_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].

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

is the standard CSC representation where the row indices for column 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

Number of stored values, including explicit zeros

data

Data array of the matrix

indices

CSC format index array

indptr

CSC format index pointer array

has_sorted_indices

Whether indices are sorted

Notes

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

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

  • efficient column slicing

  • fast matrix vector products (CSR, BSR may be faster)

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

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

Examples

>>> import numpy as np
>>> from scipy.sparse import csc_matrix
>>> csc_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, 2, 2, 0, 1, 2])
>>> col = np.array([0, 0, 1, 2, 2, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csc_matrix((data, (row, col)), shape=(3, 3)).toarray()
array([[1, 0, 4],
       [0, 0, 5],
       [2, 3, 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])
>>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray()
array([[1, 0, 4],
       [0, 0, 5],
       [2, 3, 6]])

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 matrix in the passed format.

asfptype

Upcast matrix to a floating point format (if necessary)

astype

Cast the matrix elements to a specified type.

ceil

Element-wise ceil.

check_format

check whether the matrix format is valid

conj

Element-wise complex conjugation.

conjugate

Element-wise complex conjugation.

copy

Returns a copy of this matrix.

count_nonzero

Number of non-zero entries, equivalent to

deg2rad

Element-wise deg2rad.

diagonal

Returns the kth diagonal of the matrix.

dot

Ordinary dot product

eliminate_zeros

Remove zero entries from the matrix

expm1

Element-wise expm1.

floor

Element-wise floor.

getH

Return the Hermitian transpose of this matrix.

get_shape

Get shape of a matrix.

getcol

Returns a copy of column i of the matrix, as a (m x 1) CSC matrix (column vector).

getformat

Format of a matrix representation as a string.

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) CSR matrix (row vector).

log1p

Element-wise log1p.

max

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

maximum

Element-wise maximum between this and another matrix.

mean

Compute the arithmetic mean along the specified axis.

min

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

minimum

Element-wise minimum between this and another matrix.

multiply

Point-wise multiplication by another matrix, vector, or scalar.

nonzero

nonzero indices

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 matrix without changing its data.

resize

Resize the matrix in-place to dimensions given by shape

rint

Element-wise rint.

set_shape

See reshape.

setdiag

Set diagonal or off-diagonal elements of the array.

sign

Element-wise sign.

sin

Element-wise sin.

sinh

Element-wise sinh.

sort_indices

Sort the indices of this matrix in place

sorted_indices

Return a copy of this matrix with sorted indices

sqrt

Element-wise sqrt.

sum

Sum the matrix elements over a given axis.

sum_duplicates

Eliminate duplicate matrix entries by adding them together

tan

Element-wise tan.

tanh

Element-wise tanh.

toarray

Return a dense ndarray representation of this matrix.

tobsr

Convert this matrix to Block Sparse Row format.

tocoo

Convert this matrix to COOrdinate format.

tocsc

Convert this matrix to Compressed Sparse Column format.

tocsr

Convert this matrix to Compressed Sparse Row format.

todense

Return a dense matrix representation of this matrix.

todia

Convert this matrix to sparse DIAgonal format.

todok

Convert this matrix to Dictionary Of Keys format.

tolil

Convert this matrix to List of Lists format.

trace

Returns the sum along diagonals of the sparse matrix.

transpose

Reverses the dimensions of the sparse matrix.

trunc

Element-wise trunc.

Attributes

dtype

format

has_canonical_format

Determine whether the matrix has sorted indices and no duplicates

has_sorted_indices

Determine whether the matrix has sorted indices

ndim

nnz

Number of stored values, including explicit zeros.

shape

Get shape of a matrix.

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

Return self==value.

__ge__(other)

Return self>=value.

__getattr__(attr)
__getitem__(key)
__gt__(other)

Return self>value.

__iadd__(other)
__idiv__(other)
__imul__(other)
__init__(arg1, shape=None, dtype=None, copy=False)
__isub__(other)
__iter__()[source]
__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__(other)
__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)

Return indices of maximum elements along an axis.

Implicit zero elements are also taken into account. If there are several maximum values, the index of the first occurrence is returned.

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.

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)

Return indices of minimum elements along an axis.

Implicit zero elements are also taken into account. If there are several minimum values, the index of the first occurrence is returned.

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.

Returns

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

Return type

numpy.matrix or int

asformat(format, copy=False)

Return this matrix in the passed format.

Parameters
  • format ({str, None}) – The desired matrix 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 matrix in the passed format.

asfptype()

Upcast matrix to a floating point format (if necessary)

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

Cast the 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 matrix. If copy is True, it is guaranteed that the result and this matrix do not share any memory.

ceil()

Element-wise ceil.

See numpy.ceil for more information.

check_format(full_check=True)

check whether the matrix format is valid

Parameters

full_check (bool, optional) – If True, rigorous check, O(N) operations. Otherwise basic check, O(1) operations (default True).

conj(copy=True)

Element-wise complex conjugation.

If the 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 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 matrix.

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

count_nonzero()

Number of non-zero entries, equivalent to

np.count_nonzero(a.toarray())

Unlike getnnz() and 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.

deg2rad()

Element-wise deg2rad.

See numpy.deg2rad for more information.

diagonal(k=0)

Returns the kth diagonal of the matrix.

Parameters

k (int, optional) –

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

New in version 1.0.

See also

numpy.diagonal

Equivalent numpy function.

Examples

>>> from scipy.sparse import csr_matrix
>>> A = csr_matrix([[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_matrix
>>> A = csr_matrix([[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 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 shape of a matrix.

getcol(i)[source]

Returns a copy of column i of the matrix, as a (m x 1) CSC matrix (column vector).

getformat()

Format of a matrix representation as a string.

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 matrix, in each column, or in each row.

See also

count_nonzero

Number of non-zero entries

getrow(i)[source]

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

log1p()

Element-wise log1p.

See numpy.log1p for more information.

max(axis=None, out=None)

Return the maximum of the matrix or maximum along an axis. This takes all elements into account, not just the non-zero ones.

Parameters
  • axis ({-2, -1, 0, 1, None} optional) – Axis along which the sum is computed. The default is to compute the maximum over all the matrix 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.

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_matrix of dimension a.ndim - 1.

Return type

coo_matrix or scalar

See also

min

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

numpy.matrix.max

NumPy’s implementation of ‘max’ for matrices

maximum(other)

Element-wise maximum between this and another matrix.

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

Compute the arithmetic mean along the specified axis.

Returns the average of the matrix elements. The average is taken over all elements in the 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 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.

    New 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.

    New 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)

Return the minimum of the matrix or maximum along an axis. This takes all elements into account, not just the non-zero ones.

Parameters
  • axis ({-2, -1, 0, 1, None} optional) – Axis along which the sum is computed. The default is to compute the minimum over all the matrix 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.

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_matrix of dimension a.ndim - 1.

Return type

coo_matrix or scalar

See also

max

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

numpy.matrix.min

NumPy’s implementation of ‘min’ for matrices

minimum(other)

Element-wise minimum between this and another matrix.

multiply(other)

Point-wise multiplication by another matrix, vector, or scalar.

nonzero()[source]

nonzero indices

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

Examples

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

This function performs element-wise power.

Parameters
  • n (n is a scalar) –

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

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 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 matrix being used.

Returns

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

Return type

sparse matrix

See also

numpy.matrix.reshape

NumPy’s implementation of ‘reshape’ for matrices

resize(*shape)

Resize the 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 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 matrix 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)

See reshape.

setdiag(values, k=0)

Set diagonal or off-diagonal elements of the array.

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 matrix in place

sorted_indices()

Return a copy of this matrix with sorted indices

sqrt()

Element-wise sqrt.

See numpy.sqrt for more information.

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

Sum the 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 matrix elements, returning a scalar (i.e., axis = None).

  • dtype (dtype, optional) –

    The type of the returned 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.

    New 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.

    New 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 matrix 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 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 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 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=False)

Convert this matrix to Block Sparse Row format.

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

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

tocoo(copy=True)

Convert this matrix to COOrdinate format.

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

tocsc(copy=False)[source]

Convert this matrix to Compressed Sparse Column format.

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

tocsr(copy=False)[source]

Convert this matrix to Compressed Sparse Row format.

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

todense(order=None, out=None)

Return a dense matrix representation of this 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 matrix to sparse DIAgonal format.

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

todok(copy=False)

Convert this matrix to Dictionary Of Keys format.

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

tolil(copy=False)

Convert this matrix to List of Lists format.

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

trace(offset=0)

Returns the sum along diagonals of the sparse 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)[source]

Reverses the dimensions of the sparse 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 matrix being used.

Returns

p

Return type

self with the dimensions reversed.

See also

numpy.matrix.transpose

NumPy’s implementation of ‘transpose’ for matrices

trunc()

Element-wise trunc.

See numpy.trunc for more information.

__array_priority__ = 10.1
__hash__ = None
property dtype
format = 'csc'
property has_canonical_format

Determine whether the 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

Determine whether the matrix has sorted indices

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

  • False: otherwise

ndim = 2
property nnz

Number of stored values, including explicit zeros.

See also

count_nonzero

Number of non-zero entries

property shape

Get shape of a matrix.