我正在尝试将条件应用于熊猫数据框中的列,但出现此错误:
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])
有什么想法吗 ?
这apply
是一个不好的选择,因为引擎盖下有循环,因此处理大数据时速度很慢。更好的方法是使用矢量化解决方案numpy.where
:
Cars ['Price'] = np.where(Cars ['Price'] <= 25.000, 0, 1)
或innvert
条件>
和转换为integer
用于True/False
给0/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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句