Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a DataFrame with "sign" numbers

Tags:

python

pandas

I have a DataFrame full of floats (positive and negative) and some NaN. I'd like to replace every single float number with its sign:

if it's NaN -> it remains Nan
if positive -> replace with 1
if negative -> replace with -1
if zero -> leave it as 0

Any suggestions to make this massive replacement?

Thank you in advance

like image 734
vsoler Avatar asked May 22 '16 17:05

vsoler


1 Answers

You can use np.sign:

df
Out[100]: 
     A
0 -4.0
1  2.0
2  NaN
3  0.0

import numpy as np
np.sign(df["A"])

Out[101]: 
0   -1.0
1    1.0
2    NaN
3    0.0
Name: A, dtype: float64

In order to apply to all columns, you can directly pass the dataframe:

df
Out[121]: 
          0         1         2         3
0 -2.932447 -1.686652       NaN -0.908441
1  1.254436  0.000000  0.072242  0.796944
2  2.626737  0.169639 -1.457195  1.169238
3  0.000000 -1.174251  0.660111  1.115518
4 -1.998091 -0.125095  0.000000 -0.506782

np.sign(df)
Out[122]: 
     0    1    2    3
0 -1.0 -1.0  NaN -1.0
1  1.0  0.0  1.0  1.0
2  1.0  1.0 -1.0  1.0
3  0.0 -1.0  1.0  1.0
4 -1.0 -1.0  0.0 -1.0
like image 62
ayhan Avatar answered Sep 25 '22 22:09

ayhan