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.

2 Answers2

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]]
jdehesa
  • 58,456
  • 7
  • 77
  • 121
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]])
Sheldore
  • 37,862
  • 7
  • 57
  • 71