Reputation: 163
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?
Upvotes: 3
Views: 5698
Reputation: 14399
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.
Upvotes: 2
Reputation: 26037
You can do:
t1[np.where(t2>5), 2] = 10
Syntax: array[<row>, <col>]
Upvotes: 1
Reputation: 7224
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.]])
Upvotes: 3