-1

I have table like below in Python Pandas with float64 data type:

col1
--------
245.121
NaN
44.908

And I try to create new column "col2" using below code:

data["col2"] = data.apply(lambda x: 1 if x.col1== np.nan else 0, axis = 1)

Unfortunately, when I use above code I have 0 everywhere, why ? How can I modyfi my code to achieve something like below:

col1      col2
--------
245.121  | 0
NaN      | 1
44.908   | 0

How can I do that in Python Pandas ?

bony767
  • 39
  • 4
  • 1
    Use `np.isnan(x.col1)` or `pd.isnull(x.col1)`. https://stackoverflow.com/questions/44367557/why-does-assert-np-nan-np-nan-cause-an-error – Emma Dec 08 '21 at 00:29

1 Answers1

1

Try:

data["col2"] = data.apply(lambda x: 1 if x.col1 in [np.nan] else 0, axis = 1)

This should work, while yours doesn't because it's a feature that np.nan != np.nan

richardec
  • 14,202
  • 6
  • 23
  • 49
Tortar
  • 375
  • 1
  • 13