4

I'm trying to apply a condition to a column in my pandas dataframe, but i get this error :

TypeError: 'float' object is not iterable

Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22.000,25.000,27.000,35.000]
        }

Cars = DataFrame(Cars, columns= ['Brand', 'Price'])
Cars ['Price'] = Cars ['Price'].apply(lambda x: [0 if y <= 25.000 else 1 for y in x])

Any thoughts ?

1
  • 1
    With apply, the argument to the function is a single element of the container. In other words, instead of lambda x: [0 if y <= 25.000 else 1 for y in x], you just want lambda x: 0 if x <= 25.000 else 1. Commented May 17, 2019 at 13:29

2 Answers 2

2

Here apply is bad choice, because there are loops under the hood, so slow in large data. Better is use vectorized solutions with numpy.where:

Cars ['Price'] = np.where(Cars ['Price'] <= 25.000, 0, 1)

Or innvert condition to > and cast to integer for True/False to 0/1 mapping:

Cars ['Price'] = (Cars ['Price'] > 25.000).astype(int)

print (Cars)

            Brand  Price
0     Honda Civic      0
1  Toyota Corolla      0
2      Ford Focus      1
3         Audi A4      1
Sign up to request clarification or add additional context in comments.

Comments

2

Don't iterate through the list, .apply applies the function to each element in the column!

Try this line:

Cars ['Price'] = Cars ['Price'].apply(lambda x: 0 if x <= 25.000 else 1)

1 Comment

My bad I interpreted wrong the definition of .apply

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.