[英]Extracting numerical value with special characters from a string but removing other occurrences of those characters
我正在使用 Python 和 Pandas,并且有一个包含字符串的 DataFrame 列。 我想将浮点数保留在字符串中并去掉 '- .' 在浮点数(字符串)的末尾。
到目前为止,我一直在使用下面的正则表达式来去除原始字符串中的字符和括号,但它留下了“-”和“.”。 从字符串的非数字部分到位。
示例输入字符串: 14,513.045Non-compliant with installation req.
当我尝试修改它时,这就是我得到的: 14,513.045- .
(正数字符串示例)
我也希望能够解析负数,例如: -234.670
字符串中的第一个-
用于负浮点数。 我想保持第一-
和第一.
但摆脱后续的 - 不属于该号码的那些。
这是我试图用来实现这一目标的代码:
dataframe3['single_chainage2'] = dataframe3['single_chainage'].str.replace(r"[a-zA-Z*()]",'')
但它给我留下了14,513.045- .
我认为单独使用熊猫无法完成上述操作,并且看到正则表达式是推荐的方式。
你不需要replace
,我认为你可以使用Series.str.extract
来获取你需要的字符串。
In [1]: import pandas as pd
In [2]: ser = pd.Series(["14,513.045Non-compliant with installation req.", "14,513.045- .", "-234.670"])
In [3]: pat = r'^(?P<num>-?(\d+,)*\d+(\.\d+)?)'
In [5]: ser.str.extract(pat)['num']
Out[5]:
0 14,513.045
1 14,513.045
2 -234.670
Name: num, dtype: object
并且正则表达式模式中需要一个命名组(本例中为num
)。
如果需要将其转换为数字 dtype:
In [7]: ser.str.extract(pat)['num'].str.replace(',', '').astype(float)
Out[7]:
0 14513.045
1 14513.045
2 -234.670
Name: num, dtype: float64
而不是删除您不想要的字符,只需指定您想要查找和提取的模式。 它应该不太容易出错。 你想提取一个可以是浮点数的正负数:
import re
number_match = re.search("[+-]?(\d+,?)*(\.\d+)?", 'Your string.')
number = number_match.group(0)
测试上面的代码:
test_string_positive='14,513.045Non-compliant with installation req.'
test_string_negative='-234.670Non-compliant with installation req.'
In [1]: test=re.search("[+-]?(\d+,?)*(\.\d+)?",test_string_positive)
In [2]: test.group(0)
Out[2]: '14,513.045'
In [3]: test=re.search("[+-]?(\d+,?)*(\.\d+)?",test_string_negative)
In [4]: test.group(0)
Out[4]: '-234.670'
使用此解决方案,您不想进行替换,而只想分配正则表达式匹配的值。
number_match = re.search("[+-]?(\d+,?)*(\.\d+)?", <YOUR_STRING>)
number = number_match.group(0)
dataframe3['single_chainage2'] = number
我把它分成 3 行,向你展示它在逻辑上是如何遵循的。 希望这是有道理的。
您应该用数据的字符串表示形式替换<YOUR_STRING>
的值。 至于如何从 Pandas DataFrame 中获取字符串值, 这个问题可能有一些答案。 我不确定您的 DataFrame 的实际外观,但我想df['single_chainage'][0]
应该可以工作。 基本上,如果您在 Pandas 中建立索引,它会返回一些 Pandas 特定信息,如果您只想检索字符串本身,则必须明确指定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.