我有带有多个“。”的数字字符串数据。我想删除所有“。”除小数点外

时间:2019-10-27 18:44:12

标签: python regex

嗨,我有一些数字字符串表示形式,带有“。”。作为千位和十进制标记。我想将它们转换为浮点数。


px =['1.410.00', '100.00', '1.000.00',  '1.000.000.00']

x = px[0]

def formatPxToFloat(pxStr):
    try:
        val = float(pxStr)
    except ValueError:
        val= float(re.sub("(\.)","", pxStr))   
    return val

formatPxToFloat(x)

#should return 1400.00 returns 140000

并且还尝试了其他正则表达式:

 r"(\d\.\d+)(?=\.\d+)"

任何帮助将不胜感激。

亲切问候

乔治

4 个答案:

答案 0 :(得分:0)

结合str.replacestr.count函数:

px = ['1.410.00', '100.00', '1.000.00',  '1.000.000.00']
nums = [float(s.replace('.', '', s.count('.') - 1)) for s in px]
print(nums)

输出:

[1410.0, 100.0, 1000.0, 1000000.0]

答案 1 :(得分:0)

好吧,假设小数点始终是一个后跟两位数,而其他点总是正好是3 digis,则可以使用regexp \.(\d{3})

>>> number = "2.000.999.91"
>>> re.sub("\.(\d{3})", r"\1", str)
'2000999.91'

r"\1"部分的意思是,放置第一个捕获组,在我们的例子中是\d{3},这意味着该点之后的三个字符。

希望有帮助

答案 2 :(得分:0)

您可以使用re.sub替换正则表达式匹配项。

import re
px =['1.410.00', '100.00', '1.000.00',  '1.000.000.00']
px_floats = [float(re.sub(r'\.(?=.*?\.)', '', item)) for item in px]
for px_float in px_floats:
    print(f"value: {px_float}, type:  {type(px_float)}")

输出

value: 1410.0, type:  <class 'float'>
value: 100.0, type:  <class 'float'>
value: 1000.0, type:  <class 'float'>
value: 1000000.0, type:  <class 'float'>

答案 3 :(得分:0)

尝试使用此正则表达式:

'\.(?=.*?\.)'

该正则表达式的细分如下:

\.    # '.'
(?=   # Positive lookahead
.*?   # Match anything
\.    # Search for '.'

Python中的应用程序

import pandas as pd

px = ['1.410.00', '100.00', '1.000.00',  '1.000.000.00']
px2 = pd.Series(px)
px3 = px2.str.replace(r'\.(?=.*?\.)', '')
print(px3)

输出:

0       1410.00
1        100.00
2       1000.00
3    1000000.00
dtype: object