python - 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])
有什么想法吗 ?
解决方案
这apply
是一个不好的选择,因为引擎盖下有循环,所以在大数据中速度很慢。更好的是使用矢量化解决方案numpy.where
:
Cars ['Price'] = np.where(Cars ['Price'] <= 25.000, 0, 1)
或者innvert
条件 to>
和 cast to integer
for True/False
to0/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
推荐阅读
- python - 熊猫:选择索引,然后选择多索引切片上的列
- intellij-idea - Force push keyboard shortcut in IntelliJ IDEA 2018.1
- html - 如何将模式的第一个字符与其余字符分开?
- r - Fill a polygon with gradient scale in R
- tensorflow - 在带有 AMD Radeon Pro 450 2048 MB 的 Mac High Sierra 10.13.4 上支持 GPU 的 Tensorflow?
- java - 如何将小 ORC 文件合并或合并为更大的 ORC 文件?
- logging - 将日志文件输出到集群选项
- html - Why does my footer have elements under it?
- c - AES decryption without padding in crypt file
- python - 使用带有多个参数的函数与`map`