Reputation: 1103
So let's say I have a numpy array a= np.array([1,2,3,4,5])
and a value x=4
, then I want to create a numpy array of values -1
and 1
where there is a 1
in the 4th
position and -1
everywhere else.
Here is what I tried:
for i in range(a):
if i == x:
a[i]=1
else:
a[i]=-1
Is this good?
Upvotes: 0
Views: 80
Reputation: 5707
Another alternative. Utilizes casting from bool to int.
b=2*(a==x)-1
Upvotes: 0
Reputation: 13387
Try:
import numpy as np
a= np.array([1,2,3,4,5])
x=np.where(a==4, 1, -1)
print(x)
Output:
[-1 -1 -1 1 -1]
[Program finished]
Upvotes: 2
Reputation: 331
try this:
b = np.array([1 if i == 4 else -1 for i in range(a.shape)])
Upvotes: 1
Reputation: 5745
No, this is not numpy'ish
b=-np.ones(a.shape)
b[x] = 1
Edit: added example
import numpy as np
x=3
a= np.array([1, 2, 3, 4, 5])
b=-np.ones(a.shape)
b[x] = 1
print(b)
> [-1. -1. -1. 1. -1.]
Upvotes: 4