Meraj
Meraj

Reputation: 41

Selectively negate elements in an array

I am looking for some help around 'how to selectively negate the values of an array' in numpy.

Already tried, numpy.where() and numpy.negative but not able to implement condition on selected few.

import numpy as np

arr=np.arange(11)
arr

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

Say I want to just negate all elements of the array that are between 2 and 8

array([ 0,  1,  2,  -3,  -4,  -5,  -6,  -7,  8,  9, 10])

Upvotes: 3

Views: 11576

Answers (6)

Abhinav
Abhinav

Reputation: 25

I believe this is the solution you are looking for. You can use either of the approaches.

index = arr.where((arr>2) & (arr<8))
arr[index] *= -1
print(arr)

Or

arr[(arr>2) & (arr<8)] *= -1
print(arr)

Upvotes: 1

Panda  Nah
Panda Nah

Reputation: 1

why not?

a = np.random.random(size=10)
a[2:8] = np.negative(a[2:8])

Upvotes: 0

Prayas Dixit
Prayas Dixit

Reputation: 1

This snipped should be helpful to you

c=np.where((arr>2) & (arr<8) ,arr*-1,arr)

Upvotes: 0

Anugraha Shukla
Anugraha Shukla

Reputation: 11

import numpy as np

arr = np.arange(11)

arr[3:9] = np.multiply(arr[3:9],-1)

print(arr)

Upvotes: 1

user3483203
user3483203

Reputation: 51175

Use bitwise AND to create a mask, and multiply by -1:

m = (arr > 2) & (arr < 8)
arr[m] *= -1

array([ 0,  1,  2, -3, -4, -5, -6, -7,  8,  9, 10])

Upvotes: 8

Thomas Lang
Thomas Lang

Reputation: 780

Try this:

condition = np.logical_and(arr >= 2, arr <= 8)
arr = np.select([~condition, condition], [arr, -arr])

Upvotes: 2

Related Questions