[英]How can I parse a string number to a float python
from excel I have a number in the following type: "22.024.833,02 ", so I've been trying.strip(), .replace() among others but I couldn't get a float from my code.来自 excel 我有一个以下类型的数字:“22.024.833,02”,所以我一直在尝试.strip()、.replace() 等,但我无法从我的代码中获得浮点数。
for columna, fila in mav.iterrows():
comitente = fila['Comit.']
moneda = fila['Especie']
m = fila['Operado'].strip()
m2 = m.replace('.', '')
monto = float(m2)
Result: monto = float(m2) ValueError: could not convert string to float: '22024833,02'结果:monto = float(m2) ValueError: could not convert string to float: '22024833,02'
My answer is assuming you're using .
我的回答是假设你正在使用
.
for digit separator and ,
for the decimal point.用于数字分隔符,
,
用于小数点。
m = fila['Operado'].strip() # m = "22.024.833,02"
m = m.replace('.', '') # m = "22024833,02"
m = m.replace(',', '.') # m = "22024833.02"
monto = float(m) # monto = 22024833.02
Python's float
expects no digit separator (the .
in your example), and the decimal point to be a .
Python 的
float
不需要数字分隔符(示例中的.
),小数点为.
(not a ,
as in your input). (不是 a
,
如您的输入)。
I think this is what you are looking for我想这就是你要找的
m = float(fila['Operado'].strip().replace(".","").replace(",","."))
Its better to use .
它更好地使用
.
for decimal places and ,
for the whole number part.对于小数位
,
对于整数部分。
You can try this:你可以试试这个:
for columna, fila in mav.iterrows():
comitente = fila['Comit.']
moneda = fila['Especie']
m = fila['Operado'].strip()
m2 = m.replace('.', '').replace(',', '.')
monto = float(m2)
More compact solution:更紧凑的解决方案:
for columna, fila in mav.iterrows():
comitente = fila['Comit.']
moneda = fila['Especie']
monto = float(fila['Operado'].strip().replace('.', '').replace(',', '.'))
In Python you should use .
在 Python 中,您应该使用
.
instead of ,
as decimal separator.而不是
,
作为小数分隔符。
good_float = 1.44
not_a_float = 1,22 # This will be stored as a tuple
If your input string is written with ,
as decimal separator, you can use String.replace()
method.如果您的输入字符串使用
,
作为小数分隔符,您可以使用String.replace()
方法。
>>> '3,14'.replace(',', '.')
'3.14'
If you are also using .
如果你也在使用
.
as digit separator, you can replace it with the same method.作为数字分隔符,您可以用相同的方法替换它。
>>> '1.203,14'.replace('.', ' ').replace(',', '.')
'1203,14'
Then you can finely convert the string to a float using the float
built-in function.然后,您可以使用内置的
float
function 将字符串精细地转换为浮点数。
>>> float('3,14'.replace('.', ' ').replace(',', '.'))
3.14
Remember to always write .replace('.', ' ')
before .replace(',', '.')
to avoid a mess with periods.请记住始终在
.replace(',', '.')
.replace('.', ' ')
') 以避免与句号混淆。
Your code should work now:您的代码现在应该可以工作了:
>>> float(fila['Operado'].strip().replace('.', ' ').replace(',', '.'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.