Skip to main content
`Ctrl`+`K`
scipy.sparse.

# triu

scipy.sparse.triu(A, k=0, format=None)

  Return the upper triangular portion of a sparse array or matrix.

  Returns the elements on or above the k-th diagonal of A.

    - k = 0 corresponds to the main diagonal

    - k > 0 is above the main diagonal

    - k < 0 is below the main diagonal

  Warning

  `triu` is switching to the sparse array interface.

  For the case where no input arrays are sparse, this function is switching to returning a sparse array instead of sparse matrix. Control the sparse return class by making at least one input sparse, e.g., `triu(coo_matrix(A))`, or `triu(coo_array(A))`. That removes any deprecation warnings as well. For more general information about sparrays, see Migration from spmatrix to sparray. Handling of this no sparse input case will change no earlier than v1.20.

  Parameters:
    A dense or sparse array or matrix

      Matrix whose upper trianglar portion is desired.

    k int optional

      The bottom-most diagonal of the upper triangle.

    format str

      Sparse format of the result, e.g. format=”csr”, etc.

  Returns:
    L sparse array or matrix

      Upper triangular portion of A in sparse format. Sparse array if A is a sparse array, otherwise matrix.

  See also

  `tril`

    lower triangle in sparse format

  Examples

      >>> from scipy.sparse import csr_array, triu
      >>> A = csr_array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
      ...                dtype='int32')
      >>> A.toarray()
      array([[1, 2, 0, 0, 3],
             [4, 5, 0, 6, 7],
             [0, 0, 8, 9, 0]], dtype=int32)
      >>> triu(A).toarray()
      array([[1, 2, 0, 0, 3],
             [0, 5, 0, 6, 7],
             [0, 0, 8, 9, 0]], dtype=int32)
      >>> triu(A).nnz
      8
      >>> triu(A, k=1).toarray()
      array([[0, 2, 0, 0, 3],
             [0, 0, 0, 6, 7],
             [0, 0, 0, 9, 0]], dtype=int32)
      >>> triu(A, k=-1).toarray()
      array([[1, 2, 0, 0, 3],
             [4, 5, 0, 6, 7],
             [0, 0, 8, 9, 0]], dtype=int32)
      >>> triu(A, format='csc')
      <Compressed Sparse Column sparse array of dtype 'int32'
          with 8 stored elements and shape (3, 5)>