python - 如果单元格开头有 -* 结尾有 *,则更改单元格中的值
问题描述
我有一个看起来像这样的数据框
Name salary age Id
Steve 23000 -*29* 22
Mark -*2900* 24 82
John 40000 26 -*72*
我想
Name salary age Id
Steve 23000 29 22
Mark 2900 24 82
John 40000 26 72
我努力了。
df.apply(lambda x:x[2:-1] if x.str.startwith('="') and x.str.endwith('"') else x)
我收到错误
ValueError: The truth of a series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
我想我没有到达单元格,而是将更改应用于列。
解决方案
IIUC,您要删除-*
字符:
df = df.apply(lambda c: c.str.strip('-*'))
输出:
Name salary age Id
0 Steve 23000 29 22
1 Mark 2900 24 82
2 John 40000 26 72
注意。您的单元格仍将是字符串,以转换为数字:
df = df.apply(lambda c: pd.to_numeric(c.str.strip('-*'), errors='ignore'))
推荐阅读
- docker - 如何使用 Docker 容器化 CodeIgniter 项目?
- ios - 由于未捕获的异常“NSInternalInconsistencyException”问题而终止应用程序
- firebase - 在没有存储桶的情况下在 Firebase 云功能中使用外部资源(媒体)
- c# - 使用特定类使用 Newtonsoft 反序列化 JSON
- python - 在模式中读取具有不同工作表名称的熊猫中的 excel 工作表
- google-apps-script - 谷歌表格的格式脚本
- go - 使用“go list”如何仅列出二进制文件中使用的 Go 模块?
- elasticsearch - 启动 logstash 时出现 HostUnreachableError
- x86 - 通过编辑可执行文件禁用 x86 应用程序中的按钮
- google-apps-script - 使用 WooCommerce 订单更新 Google 表格