简体   繁体   中英

Pandas convert positive number to 1 and negative number to -1

I have a column of positive and negative number. How to convert this column to a new column to realize convert positive number to 1 and negative number to -1?

You need numpy.sign

df['new'] = np.sign(df['col'])

Sample :

df = pd.DataFrame({ 'col':[-1,3,-5,7,1,0]})
df['new'] = np.sign(df['col'])
print (df)

   col  new
0   -1   -1
1    3    1
2   -5   -1
3    7    1
4    1    1
5    0    0
df[df < 0] = -1
df[df > 0] = 1

//no behaviour defined for df = 0

It's really easy to perform this task by -

For whole data frame -

    df[df < 0] = -1
    df[df > 0] = 1

For specific column -

   df['column_name'][df['column_name'] < 0] = -1
   df['column_name'][df['column_name'] > 0] = 1

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