0

In python 3 I was trying to apply lambda function to the specific DataFrame column. In original column ('fuelType') I had several types of fuel but wanted to create new column ('fuel) which would show only 3 types -> 'Premium Gasoline', 'Regular Gasoline' (those two were by far the most common), and include all other types into 'Other' category. In the end something like this worked just fine:

df['fuel'] = df['fuelType'].apply(lambda x: x if x.split()[0] in ['Premium', 'Regular'] else 'Other')

However I'm not entirely sure why something like this did not work:

df['fuel'] = df['fuelType'].apply(lambda x: x if x.split()[0] == 'Premium' or 'Regular' else 'Other')

In the second case the new column appears to be the same as the old one, but when I used this code:

df['fuel'] = df['fuelType'].apply(lambda x: x if x.split()[0] == 'Premium' else 'Other')

It worked as I expected, meaning the new column showed 'Premium Gasoline' and 'Other' categories. So it looks like I've messed up something with the 'or' statement here, but can't figure out what... Could you please help me notice what am I missing here :)

Thank you in advance!

1 Answer 1

1

The problem is that an or is not part of a comparasion. If you see x.split()[0] == 'Premium' or 'Regular'

You think x.split()[0] == ('Premium' or 'Regular')

But Python thinks (x.split()[0] == 'Premium') or 'Regular'

Now what does this expression mean?

or gives you the first expression that evaluates to true, which for strings is everything except empty string.

Therefore you either have True or 'someString' which is True or False or 'someString' which is 'someString' which is also true.

Solution:

x.split()[0] == 'Premium' or x.split()[0] == 'Regular'
Sign up to request clarification or add additional context in comments.

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.