Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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?

like image 640
xxyao Avatar asked Dec 02 '22 10:12

xxyao


2 Answers

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
like image 97
jezrael Avatar answered Dec 04 '22 09:12

jezrael


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
like image 37
Abhishek Patel Avatar answered Dec 04 '22 08:12

Abhishek Patel