Reputation: 35
I need to slice a numpy array so that I obtain an array that corresponds to the dark green areas: array
The green area is the intersection of multiple ranges in the columns and the rows. I thought of something like:
M[[1:3,5:7],[1:3,5:7]]=np.zeros(4,4)
But it doesn't work. How can I do this efficiently?
Upvotes: 1
Views: 1034
Reputation: 35
I found an answer using this matlab like array indexing with numpy on stackoverflow
I added an array to do what I want. The final code is:
rows = np.hstack((np.arange(1,3), np.arange(5,7)))
cols = np.hstack((np.arange(1,3), np.arange(5,7)))
M[np.ix_(rc,rc)]=np.zeros(4,4)
There is maybe a more efficient way to define rows and cols but this works for me
Upvotes: 2
Reputation: 604
UPDATE actually it works like this:
np.hstack((x[[1,2,5,6], 1:3], x[[1,2,5,6], 5:7]))
best option i found :
np.vstack((x[1:9:4, [1,2,5,6]], x[2:9:4, [1,2,5,6]]))
but then you would still have to inter exchange lines
Upvotes: 0
Reputation: 76
I think you just need to do each dark green section separately, so something like:
M[1:3, 5:7] = np.zeros((2,2))
Then repeat for the other dark green areas.
EDIT: I think I understand a bit more what you want to do, you want to do it more dynamically, so I think something like this would work:
ta = slice(1, 3)
tb = slice(5, 7)
slices=[ta, tb]
slices = [(s1, s2) for s1 in slices for s2 in slices] #Gives all combinations of slices
for s in slices:
M[s] = np.zeros((2,2))
Upvotes: 1