How do I check if something is None in python?

I am trying to write some code to create a new column in a dataframe(ad_clicks) that checks if one column(ad_click_timestamp) has values- if it has no values (ie column value is None), it puts False. Else, if the column does have values, it puts True in the new column. But I am stuck with how to compare the value in the lambda function as below-

lam= lambda x: False if x.isnull() else True
ad_clicks['is_click']=ad_clicks.ad_click_timestamp.apply(lam)

And it is not running. Error shown is-

AttributeError: ‘str’ object has no attribute ‘isnull’

What am I doing wrong?

if x is None: #x is whatever variable name you're using

#the opposite would be 
if x is not None:

and further reading on when to use this “is” vs == (it relates to None) https://stackoverflow.com/questions/14247373/python-none-comparison-should-i-use-is-or

@cloudsolver36218,

The problem is that you are trying to call .isnull() on the value rather than the Series or DataFrame. .apply() applies your function to each value in either the row or column that you specify.

If you want to check if that value is null, you have to use pd.isna() or pd.isnull().

Try this code:

lambda x: False if pd.isnull(x) else True

See the documentation here and here.

2 Likes