简体   繁体   中英

assign three values based on condition to pandas df column

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

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM