Putra Hidayat
Putra Hidayat

Reputation: 3

how to make a range of column negative in numpy?

Just a newbie using numpy. I have a long data but simply like this:

a 3
b 2
c 1
d 0
e 1
f 2
g 3

I want to have output:

a -3
b -2
c -1
d 0
e 1
f 2
g 3

I tried to use numpy to negate data above column2=0, but I always get error.

can anyone help me please?

Upvotes: 0

Views: 710

Answers (2)

FObersteiner
FObersteiner

Reputation: 25594

to make this slightly more general: given an array arr that you want to change sign up to (and excluding) a value v, you could

import numpy as np
arr = np.array([3,2,1,0,1,2,3])
v = 0

# find the index of the first occurrence of v:
idx = np.argmax(arr == v)

# change the sign up to index idx-
# since argmax returns 0 if v is not found, we have to check that:
if arr[idx] == v:
    arr[:idx] = arr[:idx] * -1
    # to not touch the original array, e.g.
    # arr_new = np.concatenate([arr[:idx]*-1, arr[idx:]])
# could put an else condition here, raise ValueError or sth like that    

print(arr)
# [-3 -2 -1  0  1  2  3]

Upvotes: 0

Joe
Joe

Reputation: 7131

If the values are really ascending indices then like that:

import numpy as np

a = np.arange(-3, 4)
print(a)

b = np.zeros((7, 2))
print(b)

b[:, 1] = a

Upvotes: 1

Related Questions