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 ?
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With