Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I modify apply and lambda function to create new column based on other in Python Pandas?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

How can I do that in Python Pandas ?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading