kjanko kjanko - 1 month ago 6
Python Question

Transform dataframe values

I have a pandas dataframe where all of the columns have values between -1 and 1. I wish to transform these values to either 0 or 1, depending whether the original value is positive or negative.

Is there a method that'd apply such transformation or do I have to do it by hand by iteration?

2014-02-19 -0.005585 2.273724 1.622362 2.971364 1.980529
2014-02-20 0.005761 0.139337 0.129309 0.007561 0.086854
2014-02-21 -0.001857 -0.868622 -0.555042 -0.591182 -0.488545
2014-02-24 0.006428 0.120364 0.217812 0.117301 0.358756
2014-02-25 -0.001697 0.032631 0.220509 -0.154151 0.592626


Should be

2014-02-19 0 1 1 1 1
2014-02-20 1 1 1 1 1
2014-02-21 0 0 0 0 0
2014-02-24 1 1 1 1 1
2014-02-25 0 1 1 0 1

Answer Source

Assuming the date column is the index:

(df > 0).astype('int')
Out: 
            1  2  3  4  5
2014-02-19  0  1  1  1  1
2014-02-20  1  1  1  1  1
2014-02-21  0  0  0  0  0
2014-02-24  1  1  1  1  1
2014-02-25  0  1  1  0  1

If it is not the index, you can set it with df = df.set_index('Date') where Date is the name of the column.