2

I have a sparse matrix A in Python and I want to add 14 to the first column.

A[:,0] + 14

However, I get an error message:

NotImplementedError: adding a nonzero scalar to a sparse matrix is not supported

Harold
  • 373
  • 2
  • 12

2 Answers2

1

You can add an explicit column like this:

A[:, 0] = np.ones((A.shape[0], 1))*14 + A[:, 0]
taras
  • 6,566
  • 10
  • 39
  • 50
  • If you are using a `csr_matrix` and have zeros on your first column, and you try the given approach, you get an `SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.` – leoschet Jun 19 '18 at 20:55
0

I ran into a similar situation (as described in your question title) and after some research, I found that you can manually change the shape of your matrix but then, this doesn't look like the best solution, for this reason, I started a discussion here and my final solution was to manually create the sparse matrix (ìndices, indptr and data lists) so I could add new columns, rows and change the matrix sparsity at will.

The description of your question suggests a different problem, you don't want to add a new column, but to change the value of an element from the matrix. If this alters the matrix sparsity, I would suggest you have your own ìndices, indptr and data lists. If you want to modify a non-zero element, then you can change it directly without further problems.

Also, this might be worth reading

leoschet
  • 1,697
  • 17
  • 33