Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'float' object is not iterable with apply lambda

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 ?

like image 615
Slach Avatar asked Sep 12 '25 12:09

Slach


2 Answers

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
like image 166
jezrael Avatar answered Sep 15 '25 02:09

jezrael


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)

like image 41
vurmux Avatar answered Sep 15 '25 02:09

vurmux