Assigning values to a numpy array using indices and sub indices

Viewed 197

This has bitten me a few times, and I can't tell if it's a bug or a feature.

nums = np.arange(10)
indx1 = np.array([2,4,6,8])
indx2 = np.array([0,3])

It looks like I can index nums either way

nums[indx1][indx2], nums[indx1[indx2]]

outputs (array([2, 8]), array([2, 8]))

If I want to re-assign those values, This doesn't work

nums[indx1][indx2] = 20
nums

outputting array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

But this works as expected:

nums[indx1[indx2]] = 20
nums 

outputting array([ 0, 1, 20, 3, 4, 5, 6, 7, 20, 9])

Why do I have to nest my index arrays rather than daisy-chain them?

1 Answers

Here is what I think.

Even though above two methods return the same results, they are different when you do assignment operations.


nums[indx1][indx2] can be divided into two parts temp = nums[indx] and temp[indx2].

step 1. temp = nums[indx1] slicing will create a new array return [2 4 6 8]

step 2. temp[indx2] will return [2,8]

so if you try nums[indx1][indx2] = 20, it is equivalent to

temp = nums[indx1]
print(temp)
temp[indx2] = 20
print(temp)

This will not affect the original array nums.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


Why does the second method work?

indx1[indx2] return [2, 8]

nums[[2,8]] = 20 will give you array([ 0, 1, 20, 3, 4, 5, 6, 7, 20, 9]). It works because you assign value to the original array nums.

Overall, the first one cannot access to the memory of nums but the second does.

Related