I have a DataFrame:df as following:
row id name age url
1 e1 tom NaN http1
2 e2 john 25 NaN
3 e3 lucy NaN http3
4 e4 tick 29 NaN
I want to change the NaN to be 0, else to be 1 in the columns: age, url. My code is following, but it is wrong.
import Pandas as pd
df[['age', 'url']].applymap(lambda x: 0 if x=='NaN' else x)
I want to get the following result:
row id name age url
1 e1 tom 0 1
2 e2 john 1 0
3 e3 lucy 0 1
4 e4 tick 1 0
Thanks for your help!
Use
np.where
withpd.notnull
to replace the missing and valid elements with0
and1
respectively:You can use
where
withfillna
and condition byisnull
:Or
numpy.where
withisnull
:Fastest solution with
notnull
andastype
:EDIT:
I try modify your solution:
Timings:
len(df)=4k
: