Reputation: 554
I have a pandas df that contains a column of positive, negative nos and zeros. I wanted to crate another column which is 1 if no is > 0, -1 if no is < 0 and 0 if the number is 0.
I am trying to do this using a for loop for each row but it is taking too long. I wanted to know if there was a faster way to do this. I also wanted to know if the same logic could be extended to positive and negative timedelta objects.
Thank you.
My final df should look like this:
df = pd.DataFrame({'a':[1, 2, -1, 0, -2], 'b':[1, 1, -1, 0, -1]})
a b
0 1 1
1 2 1
2 -1 -1
3 0 0
4 -2 -1
where b is the col to assign based on values of a
Upvotes: 2
Views: 803
Reputation: 3739
try using np.where and provide conditions
import numpy as np
df['b']= np.where(df['a']>0,1,
np.where(df['a']<0,-1,0))
a b
0 1 1
1 2 1
2 -1 -1
3 0 0
4 -2 -1
m1= df['a'] >0
m2= df['a'] <0
df['b'] = np.select([m1, m2],
[ 1, -1],
default=0)
Upvotes: 2
Reputation: 323276
Here is one way numpy
sign
np.sign(df.a)
Out[118]:
0 1
1 1
2 -1
3 0
4 -1
Name: a, dtype: int64
df['b'] = np.sign(df.a)
Upvotes: 3