You can formulate this at the purely linear algebra level in terms of csr matrix multplications and a matrix addition, which are fast. I have found this to be the fastest and most memory efficient method in scipy on my laptop.
Specifically, let $M$ be the original matrix, and $M'$ be the modified version with rows and columns associated with boundary nodes zeroed out, except for the diagonal entry in which the value of 1 is placed. Then
$$M' = I_\text{interior} ~ M ~ I_\text{interior} + I_\text{boundary},$$
where $I_\text{interior}$ is the diagonal matrix with ones in locations corresponding to interior degrees of freedom and zeros elsewhere, and contrarily $I_\text{boundary}$ is the diagonal matrix with ones in the locations corresponding to the boundary degrees of freedom and zeros elsewhere.
So, the overall strategy is:
Form the diagonal matrices $I_\text{interior}$ and $I_\text{boundary}$.
Convert $I_\text{interior}$ and $I_\text{boundary}$ to CSR format.
Form the modified matrix $M' = I_\text{interior} ~ M ~ I_\text{interior} + I_\text{boundary},$.
Here is the code that I use:
def dirichlet_zero_matrix_modification(matrix, dirichlet_zero_dofs):
"""Enforces dirichlet zero B.C.'s by zeroing-out rows and columns
associated with dirichlet dofs, and putting 1 on the diagonal there."""
N = matrix.shape[1]
chi_interior = np.ones(N)
chi_interior[dirichlet_zero_dofs] = 0.0
I_interior = sps.spdiags(chi_interior, [0], N, N).tocsr()
chi_boundary = np.zeros(N)
chi_boundary[dirichlet_zero_dofs] = 1.0
I_boundary = sps.spdiags(chi_boundary, [0], N, N).tocsr()
matrix_modified = I_interior * matrix * I_interior + I_boundary
return matrix_modified
In my experience with scipy, expressing matrix manipulations in terms of higher-level linear algebraic operations (where possible) almost always yields better performance, compared to other methods that actually manipulate matrix entries or slices. In other languages and frameworks this may not be the case.
petsc4py
if you're eventually going to be solving large-scale problems. $\endgroup$