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

Question:

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?

Asked By: xxyao

||

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
Answered By: jezrael
df[df < 0] = -1
df[df > 0] = 1

no behaviour defined for df == 0

Answered By: Vj-

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
Answered By: Abhishek Patel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.