首页 > 解决方案 > 如何从字符串中删除某些符号?

问题描述

我对正则表达式有一些问题。我有一个包含金额的数据集,在某些行中有一个奇数分隔符。我需要一个正则表达式来仅删除奇数分隔符。

例如,这是我拥有的数据:

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 进行数据分析。

请帮助正则表达式。谢谢!

标签: pythonregexpandas

解决方案


好吧,如果你的数据最后有 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 更新了答案。


推荐阅读