python - 如何从字符串中删除某些符号?
问题描述
我对正则表达式有一些问题。我有一个包含金额的数据集,在某些行中有一个奇数分隔符。我需要一个正则表达式来仅删除奇数分隔符。
例如,这是我拥有的数据:
user_id sum
1 10.10
2 154.24
3 19.565.02
4 2.142.00
预期的结果是:
user_id sum
1 10.10
2 154.24
3 19565.02
4 2142.00
5 1.99
我使用 python 和 pandas lib 进行数据分析。
请帮助正则表达式。谢谢!
解决方案
好吧,如果你的数据最后有 2 个小数位,你可以跳过正则表达式,只使用 python。
例如,假设您将所有数据放入一个列表(否定标题行),您可以执行以下操作来修复数据集:
dirty = ['10.10', '154.24', '19.565.02', '2.142.00', '1.99']
# this is a list comprehension that replaces the any '.' with '' in all
# but the last three characters of your strings
clean = [item[:-3].replace('.', '') + item[-3:] for item in dirty]
>>> clean
['10.10', '154.24', '19565.02', '2142.00', '1.99']
感谢@match 更新了答案。
推荐阅读
- android - 如何检查联系人是否下载了我的应用程序?
- javascript - 更改谷歌地图上的地图框
- r - 如何在R中使用逻辑向量
- android - 如何使用 RecyclerView 传输小部件?
- smalltalk - 点“。”的用法 在 Smalltalk
- javascript - Javascript nodeJs Postgres pg 单元测试
- spring-webflux - 在 Reactor 中使用 Flux.push() 丢失一些项目
- sql - 如果某些值不匹配,如何返回默认行?
- c++ - c++ 编译器如何找到外部变量?
- java - 从 RestController 使用 OAuth2RestTemplate 时出现 InsufficientAuthenticationException