1

I am trying to do some matrix calculations with numpy and some sparse matrices. For that I want to ignore the zeros in my matrix and just access some values, but I also need to overwrite them.

import numpy as np

a=np.random.rand(5,5)
#does not change a:
a[[1,2],...][...,[1,2]]=np.array([[0,0],[0,0]])
#just changes (1,1) and (2,2)
a[[1,2],[1,2]]=np.array([0,0])

I would like to overwrite [1,1],[1,2],[2,1],[2,2] with zeros.

4
  • What exactly is the issue here? Whats wrong with a[[1,2],[1,2]]=np.array([0,0])? Commented Jan 9, 2019 at 11:25
  • It just overwrites (1,1) and (2,2), but I would like to overwrite (1,1),(1,2),(2,1) and (2,2)! Commented Jan 9, 2019 at 11:26
  • a[[[1], [2]], [1,2]]= 0 or a[np.ix_([1,2], [1,2])]=0 Commented Jan 9, 2019 at 11:30
  • stackoverflow.com/questions/19161512/numpy-extract-submatrix this answers my question. Commented Jan 9, 2019 at 11:33

2 Answers 2

3

I think you need something like this:

import numpy as np

a = np.arange(25).reshape((5, 5))
i, j = np.ix_([1, 2], [1, 2])
a[i, j] = np.zeros((2, 2))
print(a)
# [[ 0  1  2  3  4]
#  [ 5  0  0  8  9]
#  [10  0  0 13 14]
#  [15 16 17 18 19]
#  [20 21 22 23 24]]
Sign up to request clarification or add additional context in comments.

Comments

0

One general way for any given list of indices could be to simply loop over your index pairs where you want to assign 0

import numpy as np

a=np.random.rand(5,5)
indices = [[1,1],[1,2],[2,1],[2,2] ]

for i in indices:
    a[tuple(i)] = 0

print (a)

array([[0.16014178, 0.68771817, 0.97822325, 0.30983165, 0.60145224],
   [0.10440995, 0.        , 0.        , 0.09527387, 0.38472278],
   [0.93199524, 0.        , 0.        , 0.11230965, 0.81220929],
   [0.91941358, 0.96513491, 0.07891327, 0.43564498, 0.43580541],
   [0.94158242, 0.78145344, 0.73241028, 0.35964791, 0.62645245]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.