0

could anyone explain me the reson why indexing the array using a list and using [x:x] lead to a very different result when manipulating numpy arrays?

Example:

a = np.array([[1,2,3,4],[3,4,5,5],[4,5,6,3], [1,2,5,5], [1, 2, 3, 4]]) 
print(a, '\n')

print(a[[3, 4]][:1][:, 1])
a[[3, 4]][:1][:, 1] = 99
print(a, '\n')


print(a[3:4][:1][:, 1])
a[3:4][:1][:, 1] = 99
print(a, '\n')

Output:

[[1 2 3 4]
 [3 4 5 5]
 [4 5 6 3]
 [1 2 5 5]
 [1 2 3 4]] 

[2]
[[1 2 3 4]
 [3 4 5 5]
 [4 5 6 3]
 [1 2 5 5]
 [1 2 3 4]] 

[2]
[[ 1  2  3  4]
 [ 3  4  5  5]
 [ 4  5  6  3]
 [ 1 99  5  5]
 [ 1  2  3  4]] 

Is there a way to modify the array when indexing with a list?

3
  • 1
    Have you read about copy versus view in indexing? Advanced versus basic indexing? a[[3, 4]] creates a copy. a[3:4] a view. Try when indexing to use the form that indexes all dimensions at once, rather than chaining them. Especially when trying to set values. Commented Feb 18, 2021 at 18:29
  • @hpaulj thanks for the comment, ok, it makes much more sense now. However, I would still like to use advanced/fancy indexing, and modify the underlying array, like what I would get with a view. Is there a way to do that? Commented Feb 18, 2021 at 21:44
  • You have to combine the indices into one call. Commented Feb 18, 2021 at 21:52

1 Answer 1

1

Create an index that selects the desired elements without chaining:

In [114]: a[[3,4],1]=90
In [115]: a
Out[115]: 
array([[ 1,  2,  3,  4],
       [ 3,  4,  5,  5],
       [ 4,  5,  6,  3],
       [ 1, 90,  5,  5],
       [ 1, 90,  3,  4]])
Sign up to request clarification or add additional context in comments.

Comments

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.