3

I have a numpy array. I want to modify one array index by the chosen elements of another array. For example:

import numpy as np
t1 = np.ones((10,3))
t2 = np.arange(10)
t1[np.where(t2>5)][:,2] = 10
print(t1)

What I want t1 is:

array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 10.],
       [1., 1., 10.],
       [1., 1., 10.],
       [1., 1., 10.]])

But the output of t1 is:

array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])

What the problem there?

3 Answers 3

3

It's backwards, it should be:

t1[:,2][np.where(t2>5)] = 10

output:

array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1., 10.],
       [ 1.,  1., 10.],
       [ 1.,  1., 10.],
       [ 1.,  1., 10.]])
Sign up to request clarification or add additional context in comments.

Comments

2

The most pythonic way to do this is probably

t1[:, 2] = np.where(t2 > 5,       # where t2 > 5
                    10,           # put 10
                    t1[:, 2])     # into the third column of t1

Besides added clarity, for very large objects this will have a time benefit, as there is no creation of an intermediate indexing array np.where(t2 > 5) and no resulting intermediate callbacks to that python object - everything is done in-place with c-compiled code.

1 Comment

where() for the multidimensional case simply decides which array to pull from (second arg or third arg) based on the value of the first arg, so the into the third column of t1 comment probably should point to the left side of the = on the first line
1

You can do:

t1[np.where(t2>5), 2] = 10

Syntax: array[<row>, <col>]

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.