0

I'd like to replace the last N columns of a Numpy array by zeroes.

a = numpy.tile([1,2,3,4], (4,1))

array([[1, 2, 3, 4],
       [1, 2, 3, 4],
       [1, 2, 3, 4],
       [1, 2, 3, 4]])

To replace the last, I do:

a[:,-1] = 0

To replace the last 2, I would do

a[:,-2:-1] = 0

but this only replaces the penultimate column

array([[1, 2, 0, 4],
       [1, 2, 0, 4],
       [1, 2, 0, 4],
       [1, 2, 0, 4]])

Can you please explain why? What should I do to get what I want?

Thanks

jpp
  • 159,742
  • 34
  • 281
  • 339

1 Answers1

2

When doing a[:,-2:-1] = 0 you are picking from the 1 before the last column, until the last column, not including the last column.

What you are looking for is a[:,-2:] = 0 , which will pick all the columns from -2 to the end. Similarly, a[:,-3:-1] will pick the 2 middle columns.

Dinari
  • 2,487
  • 13
  • 28