我有一个带数据的CSV文件,想要在Python中读取。我获取了包含字符串"2,5
"的列表。现在,使用float("2,5")
是不起作用的,因为它具有错误的小数标记。
如何将其作为2.5
读入Python?
我有一个带数据的CSV文件,想要在Python中读取。我获取了包含字符串"2,5
"的列表。现在,使用float("2,5")
是不起作用的,因为它具有错误的小数标记。
如何将其作为2.5
读入Python?
您可以以区域设置为基础进行处理:
import locale
# Set to users preferred locale:
locale.setlocale(locale.LC_ALL, '')
# Or a specific locale:
locale.setlocale(locale.LC_NUMERIC, "en_DK.UTF-8")
print locale.atof("3,14")
在使用这个方法之前,请阅读此部分内容。
float("2,5".replace(',', '.'))
在大多数情况下可用。
如果value
是一个较大的数字,而千位分隔符使用了.
,你可以:
将所有的逗号替换为点号:value.replace(",", ".")
移除除最后一个点号以外的所有点号:value.replace(".", "", value.count(".") -1)
Pandas原生支持此功能:
df = pd.read_csv(r'data.csv', decimal=',')
请查看 http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
read_html
,如果你不替换thousands
的值,可能会出现解析错误,因为它默认为逗号,如果未指定的话。
df = pd.read_csv(r'data.csv', decimal=',', thousands='.')
- undefinedimport re
decmark_reg = re.compile('(?<=\d),(?=\d)')
ss = 'abc , 2,5 def ,5,88 or (2,5, 8,12, 8945,3 )'
print ss
print decmark_reg.sub('.',ss)
结果
abc , 2,5 def ,5,88 or (2,5, 8,12, 8945,3 )
abc , 2.5 def ,5.88 or (2.5, 8.12, 8945.3 )
尝试将所有的十进制逗号替换为十进制点:
floatAsStr = "2,5"
floatAsStr = floatAsStr.replace(",", ".");
myFloat = float(floatAsStr)
当然,replace
函数可以作用于任何子串,因为Python不区分字符和字符串。
floatAsStr
并没有好到哪里去。:-P - Vekyvalue.replace('.', '#').replace(',', '.').replace('#', ',')
但是,如果您想从字符串转换为浮点数,您可以只需删除任何点,并用点替换任何逗号。
float(value.replace('.', '').replace(',', '.'))
我认为这是最容易理解的解决方案。
首先,您必须确保提供数字时使用的语言环境。如果未能这样做,那么肯定会出现随机问题。
import locale
loc = locale.getlocale() # get and save current locale
# use locale that provided the number;
# example if German locale was used:
locale.setlocale(locale.LC_ALL, 'de_DE')
pythonnumber = locale.atof(value)
locale.setlocale(locale.LC_ALL, loc) # restore saved locale
通常在某个库例程中调用setlocale()是一个不好的想法,因为它会影响整个程序。保存和恢复它几乎同样糟糕:它很昂贵,并且会影响其他线程,在设置被恢复之前运行。
- oglopdef tolerant_monetary_float (x, max_decimals = 2):
num_dot = x.count ('.')
num_com = x.count (',')
if not num_dot:
# no dot
if not num_com:
# no dot, no comma
return float (x)
if num_com > 1:
# more than one comma
return float (x.replace (',', ''))
# 1 comma: its ambiguous: 1,000 can mean 1000 or 1.0
if len (x) - x.find (',') -1 <= max_decimals:
# assume the comma is decimal separator
return float (x.replace (',', '.'))
# assume comma is thousand separator
return float (x.replace (',', ''))
if not num_com:
# no comma
if not num_dot:
# no dot, no comma
return float (x)
if num_dot > 1:
# more than one dot
return float (x.replace ('.', ''))
# 1 dot: its ambiguous: 1.000 can mean 1000 or 1.0
if len (x) - x.find ('.') -1 <= max_decimals:
# assume the dot is decimal separator
return float (x)
# assume dot is thousand separator
return float (x.replace ('.', ''))
# mix of dots and commas
if num_dot > 1 and num_com > 1:
return ValueError (f'decimal number cannot have a mix of "," and ".": {x}')
ix_dot = x.find ('.')
ix_com = x.find (',')
if ix_dot < ix_com:
# dot is before comma: 1.000,35
return float (x.replace ('.', '').replace (',', '.'))
# comma is before dot: 1,000.35
return float (x.replace (',', ''))
if __name__ == "__main__":
assert (tolerant_monetary_float ('1') == 1.0)
assert (tolerant_monetary_float ('1.2345') == 12345.0)
assert (tolerant_monetary_float ('1.234') == 1234.0)
assert (tolerant_monetary_float ('1.23') == 1.23)
assert (tolerant_monetary_float ('1.2') == 1.2)
assert (tolerant_monetary_float ('1,2345') == 12345.0)
assert (tolerant_monetary_float ('1,234') == 1234.0)
assert (tolerant_monetary_float ('1,23') == 1.23)
assert (tolerant_monetary_float ('1,2') == 1.2)
assert (tolerant_monetary_float ('1234,5') == 1234.5)
assert (tolerant_monetary_float ('1.234,5') == 1234.5)
assert (tolerant_monetary_float ('1,234.5') == 1234.5)
assert (tolerant_monetary_float ('1,234,567.85') == 1234567.85)
assert (tolerant_monetary_float ('1.234.567,85') == 1234567.85)