0

I'm facing a problem when trying to assign a specific value to a 100x100 2d array. I want it to be zero everywhere except along two segments: first line from the 25th to the 75th and last column from the 25th row to the 75th.

I tried doing it using the ": looping", I mean:

my_array[0][25:75] = 1.
my_array[25:75][99] = 1.

but the second line returns me the error:

IndexError: index 99 is out of bounds for axis 0 with size 50

As if it was first cutting an array of length 50 (75-25) and then assigning with it.

Of course I can get what I want using:

for x in xrange(25,75):
    my_array[x][-1] = 1.

But, out of curiosity, how could I get it done with : manipulation?

1 Answer 1

2

Put both array slices inside the same square brackets. Making your problem smaller so it's easier to show:

>>> my_array = np.zeros((10,10))
>>> my_array[0, 2:7] = 1
>>> my_array[2:7, -1] = 1
>>> my_array
array([[ 0.,  0.,  1.,  1.,  1.,  1.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

What's happening now is that you're requesting a 50-row slice of this array, and then the [99] is trying to get the 99th row of that, but there are only 50.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, I'll accept your answer as soon as possible.

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.