2

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

2 Answers 2

3

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

3 Comments

Thanks. Is there any way to do this for timedelta objects. I tried it but it doesn't work
@Moshee np.sign( (df.a / np.timedelta64(1, 'D')).astype(int))
2

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

Solution by @rafaelc

m1= df['a'] >0
m2= df['a'] <0


df['b'] = np.select([m1, m2],
                    [ 1, -1], 
                    default=0)

4 Comments

For multiple conditions, prefer np.select instead of nested np.where
let me modify a little
@rafaelc thanks for the suggestion .I have add np.select
@WeNYoBen thanks I actually don't use np.select more so that's why I was not familiar with default

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.