1

I have a bunch of numpy arrays that can differ in shape:

[[1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1]]

I need to select and store the indices into a variable so that I can change the array into:

[[1, 1, 1, 1, 1],
 [1, 1, 1, 1, 0],
 [1, 1, 1, 1, 0],
 [0, 0, 0, 0, 0]]

I can grab the vertical indices:

idx = np.s_[1:4, 3]

But I can't figure out how to add all of the indices from the last row and store them into idx

Update

I want the indices. There are times when I need to reference the values at those indices and there are times when I want to change the values at those indices. Having the indices will allow me the flexibility to do both.

slaw
  • 6,591
  • 16
  • 56
  • 109
  • 1
    I want the indices. There are times when I need to reference the values at those indices and there are times when I want to change the values at those indices. Having the indices will allow me the flexibility to do both. – slaw Jan 02 '19 at 13:44

2 Answers2

0

This isn't quite using slices like you had, but numpy allows you to index with lists so you can store all the coordinates you want to change.

A = np.ones((4,5))

col = np.zeros(7,dtype='int')
row = np.zeros(7,dtype='int')

col[:5] = np.arange(5)
col[5:] = 4

row[:5] = 3
row[5:] = np.arange(1,3)

A[row,col] = 0

You could also use two slices idx1 = np.s_[1:4,3] and idx2 = np.s_[3,0:5] and apply them both.

overfull hbox
  • 747
  • 3
  • 10
0

I'm not aware of a built-in NumPy method, but perhaps this will do:

import numpy as np

a = np.random.rand(16).reshape((4, 4))   # Test matrix (4x4)
inds_a = np.arange(16).reshape((4, 4))   # Indices of a
idx = np.s_[0:3, 3]     # Vertical indices
idy = np.s_[3, 0:3]     # Horizontal indices

# Construct slice matrix
bools = np.zeros_like(a, dtype=bool)
bools[idx] = True
bools[idy] = True

print(a[bools])         # Select slice from matrix
print(inds_a[bools])    # Indices of sliced elements
MPA
  • 1,878
  • 2
  • 26
  • 51