user42493
user42493

Reputation: 1103

efficient way to manipulating numpy array

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

Answers (4)

ilmarinen
ilmarinen

Reputation: 5707

Another alternative. Utilizes casting from bool to int.

b=2*(a==x)-1

Upvotes: 0

Georgina Skibinski
Georgina Skibinski

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

Milad Barazandeh
Milad Barazandeh

Reputation: 331

try this:

b = np.array([1 if i == 4 else -1 for i in range(a.shape)])

Upvotes: 1

Lior Cohen
Lior Cohen

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

Related Questions