1

I have two alternating columns where one and only one of them is NaN, while the other is populated, and vice-verse. Example:

            A           B
2010-01-04  NaN         0.000000
2010-01-05  NaN         0.001561
2010-01-06  NaN         0.003196
2010-01-07  NaN         0.006061
2010-01-08  NaN         0.008041
2010-01-11  NaN         0.009228
2010-01-12  NaN         0.008100
2010-01-13  NaN         0.008549
2010-01-14  NaN         0.009624
2010-01-15  NaN         0.008482
2010-01-19  0.006729    NaN
2010-01-20  0.005514    NaN
2010-01-21  -0.000830   NaN
2010-01-22  -0.008367   NaN
2010-01-25  -0.014079   NaN
2010-01-26  -0.019819   NaN
2010-01-27  -0.022431   NaN

What would be the quickest way to convert the columns with NaN into 0, and any nonzero into 1? For example, on the previous data, it would look like:

            A  B
2010-01-04  0  1
2010-01-05  0  1
2010-01-06  0  1
2010-01-07  0  1
2010-01-08  0  1
2010-01-11  0  1
2010-01-12  0  1
2010-01-13  0  1
2010-01-14  0  1
2010-01-15  0  1
2010-01-19  1  0
2010-01-20  1  0
2010-01-21  1  0
2010-01-22  1  0
2010-01-25  1  0
2010-01-26  1  0
2010-01-27  1  0
Scott Crooks
  • 1,523
  • 4
  • 24
  • 39

1 Answers1

2
print(df.notna().astype(int))

Prints:

            A  B
2010-01-04  0  1
2010-01-05  0  1
2010-01-06  0  1
2010-01-07  0  1
2010-01-08  0  1
2010-01-11  0  1
2010-01-12  0  1
2010-01-13  0  1
2010-01-14  0  1
2010-01-15  0  1
2010-01-19  1  0
2010-01-20  1  0
2010-01-21  1  0
2010-01-22  1  0
2010-01-25  1  0
2010-01-26  1  0
2010-01-27  1  0
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91