Fede
Fede

Reputation: 1716

replace values in dataframe with zeros and ones

I want to relace values in a dataframe, with a 0 where is a NaN value and with 1 where is a value.

here is my data:

 AA      AAPL     FB      GOOG      TSLA       XOM
Date                                                               
2018-02-28       NaN  0.068185    NaN       NaN -0.031752       NaN
2018-03-31 -0.000222       NaN    NaN       NaN       NaN -0.014920
2018-04-30  0.138790       NaN    NaN       NaN  0.104347       NaN
2018-05-31       NaN  0.135124  0.115       NaN       NaN       NaN
2018-06-30       NaN       NaN    NaN  0.028258  0.204474       NaN
2018-07-31       NaN  0.027983    NaN  0.091077       NaN       NaN
2018-08-31  0.032355  0.200422    NaN       NaN       NaN       NaN
2018-09-30       NaN -0.008303    NaN       NaN       NaN  0.060496
2018-10-31       NaN -0.030478    NaN       NaN  0.274011       NaN
2018-11-30       NaN       NaN    NaN  0.016401  0.039013       NaN
2018-12-31       NaN       NaN    NaN -0.053745 -0.050445       NaN

Upvotes: 2

Views: 52

Answers (3)

ALollz
ALollz

Reputation: 59519

Cast the Boolean values to int.

df.notnull().astype(int)

            AA  AAPL  FB  GOOG  TSLA  XOM
2018-02-28   0     1   0     0     1    0
2018-03-31   1     0   0     0     0    1
2018-04-30   1     0   0     0     1    0
2018-05-31   0     1   1     0     0    0
2018-06-30   0     0   0     1     1    0

Upvotes: 2

Space Impact
Space Impact

Reputation: 13255

Use mask and fillna:

df = df.mask(df.notna(), 1).fillna(0, downcast='infer')

Upvotes: 2

meW
meW

Reputation: 3967

Use:

df[df.notnull() == True] = 1 
df.fillna(0, inplace=True)

Upvotes: 2

Related Questions