title: Remove/set the non-zero diagonal elements of a sparse matrix in scipy
body: <p>Say I would like to remove the diagonal from a <code>scipy.sparse.csr_matrix</code>. Is there an efficient way of doing so? I saw that in the <code>sparsetools</code> module there are <code>C</code> functions to return the diagonal.</p>
  
  <p>Based on other SO answers <a href="https://stackoverflow.com/questions/12129948/scipy-sparse-set-row-to-zeros">here</a> and <a href="https://stackoverflow.com/questions/19784868/what-is-most-efficient-way-of-setting-row-to-zeros-for-a-sparse-scipy-matrix">here</a> my current approach is the following:</p>
  
  
  
  <pre class="lang-python prettyprint-override"><code>def csr_setdiag_val(csr, value=0):
      """Set all diagonal nonzero elements
      (elements currently in the sparsity pattern)
      to the given value. Useful to set to 0 mostly.
      """
      if csr.format != "csr":
          raise ValueError('Matrix given must be of CSR format.')
      csr.sort_indices()
      pointer = csr.indptr
      indices = csr.indices
      data = csr.data
      for i in range(min(csr.shape)):
          ind = indices[pointer[i]: pointer[i + 1]]
          j =  ind.searchsorted(i)
          # matrix has only elements up until diagonal (in row i)
          if j == len(ind):
              continue
          j += pointer[i]
          # in case matrix has only elements after diagonal (in row i)
          if indices[j] == i:
              data[j] = value
  </code></pre>
  
  <p>which I then follow with</p>
  
  <pre class="lang-python prettyprint-override"><code>csr.eliminate_zeros()
  </code></pre>
  
  <p>Is that the best I can do without writing my own <code>Cython</code> code?</p>