0

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?

4
  • Yes its good, whats your concrete question? Commented Oct 23, 2019 at 15:20
  • Ok cool, is there a way to do it in one line of code? Commented Oct 23, 2019 at 15:21
  • Yes, remove breaklines Commented Oct 23, 2019 at 15:22
  • range(a) doesn't work in your example. It would need to be range(len(a)) Commented Oct 23, 2019 at 15:26

4 Answers 4

4

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.]
Sign up to request clarification or add additional context in comments.

2 Comments

Or b=-np.ones(a.shape, dtype=int) if ints are required, as otherwise they're floats
Construction of b could be slightly optimized with np.full_like(a, -1). Less operations, less mem consumed.
2

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]

Comments

1

try this:

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

Comments

0

Another alternative. Utilizes casting from bool to int.

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

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.