python - 对 Pandas 数据框的所有元素应用 if/then 条件
问题描述
我需要对 Pandas Dataframe 中的每个元素应用一个非常简单的 if/then 函数。
如果任何元素的值超过 0.5,我需要返回 1。否则,我需要返回 0。
使用 lambda 函数,这似乎非常简单,但每次我尝试时都会出错:'ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()'
到目前为止,我有:
df_new = df.apply(lambda x: 1 if x > 0.5 else 1)
我会很感激任何帮助。
解决方案
您应该applymap
改用,因为您希望对数据框中的每个元素执行操作,而不是对每一列执行操作,这就是这样apply
做的。
df = pd.DataFrame({"A": [0.1, 0.2, 0.5, 0.6, 0.7],
"B": [0.75, 0.85, 0.2, 0.9, 0.0],
"C": [0.2, 0.51, 0.49, 0.3, 0.1]})
print(df)
A B C
0 0.1 0.75 0.20
1 0.2 0.85 0.51
2 0.5 0.20 0.49
3 0.6 0.90 0.30
4 0.7 0.00 0.10
df_new = df.applymap(lambda x: 1 if x > 0.5 else 0)
print(df_new)
A B C
0 0 1 0
1 0 1 1
2 0 0 0
3 1 1 0
4 1 0 0
推荐阅读
- google-cloud-platform - 无法从 Google Function 连接到 MongoDB Atlas
- qt - 如何找到消息的来源,由 Qt 输出?
- mysql - 在codeigniter mysql中格式化int datetime
- php - 如何使用 MIME 而不是仅检测图像扩展名的允许文件类型执行安全图像上传
- python - 在 python 中从 R data.table 访问数据的推荐方法是什么?我可以避免将数据写入光盘吗?
- android - 如何在 Kotlin 扩展函数中使用泛型
- python - Telegram Python Bot,它使用命令中的参数解释某些首字母缩略词
- heroku - 如何将 webhook 部署到 Heroku?
- amazon-s3 - 使用 s3 连接的 EKS 上的 Airflow 1.10.6 kubernetes 执行器,任务通过测试但 dag 运行失败
- pandas - Pandas - 比较两个数据框并查找已更改的行