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?
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
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
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