首页 > 解决方案 > TypeError: 'float' 对象不能用 apply lambda 迭代

问题描述

我正在尝试将条件应用于我的 pandas 数据框中的列,但出现此错误:

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])

有什么想法吗 ?

标签: pythonpandasdataframe

解决方案


apply是一个不好的选择,因为引擎盖下有循环,所以在大数据中速度很慢。更好的是使用矢量化解决方案numpy.where

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

或者innvert条件 to>和 cast to integerfor True/Falseto0/1映射:

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

推荐阅读