2

I was going to use a lambda function that returns 'Purchase' for not null values and returns 'No Purchase' else. I am not be sure which one to use. If I use the first one it works. However, I can't understand why I have to use the first one instead of the second one.

df['is_purchase'] = df.click_day.apply(lambda x: 'Purchase' if pd.notnull(x) else 'No Purchase')
df['is_purchase'] = df.click_day.apply(lambda x: 'Purchase' if pd.notnull(x)==True else 'No Purchase')

Can someone please explain why the first one is true?

7
  • 1
    What is the problem, error message? Commented Dec 25, 2020 at 17:36
  • That is interesting, but why would you want to use the second variant anyway, when the first one is clearly better code? Commented Dec 25, 2020 at 17:36
  • 1
    pd.notnull(x)==True is implied by pd.notnull(x), so the second is more wordy. Commented Dec 25, 2020 at 17:37
  • There is no error message. I was studying on a website, and this is a practice work. As an answer, it uses the first one. I just couldn't understand why the first one instead of the second. Commented Dec 25, 2020 at 17:37
  • So they both work the same way, then? Commented Dec 25, 2020 at 17:38

3 Answers 3

2

Because if pd.notnull(x)==True is bad style, in any programming language. The ==True is already implied, so why include it?

Sign up to request clarification or add additional context in comments.

Comments

2

If something has the logical value True, then the result of comparison it with True:

something == True

is True, too.


The opposite is true, too: If something == True, then something has the True logical value. So the form

if something:

means the same as

if something == True:

To understand why the shortest form is preferred, compare

if (a < 10) == True:

with

if a < 10:

Which one is more natural?

Comments

1

Here's a visual example of what has already been explained:

In [45]: s = pd.Series([True, False])

In [46]: s
Out[46]: 
0     True
1    False
dtype: bool

In [47]: s2 = s == True

In [48]: s2
Out[48]: 
0     True
1    False
dtype: bool

In [49]: s.equals(s2)
Out[49]: True

Saying if some_bool is the same as saying if some_bool == True, so there's no need to type it out explicitly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.