[英]Is there a faster way to cast a string to a float in python?
我正在从文件中读取数字并将其转换为浮点数。 数字看起来像这样。
1326.617827, 1322.954823, 1320.512821, 1319.291819...
我用逗号将每一行分开,然后通过列表理解来创建浮动列表。
def listFromLine(line):
t = time.clock()
temp_line = line.split(',')
print "line operations: " + str(time.clock() - t)
t = time.clock()
ret = [float(i) for i in temp_line]
print "float comprehension: " + str(time.clock() - t)
return ret
输出看起来像这样
line operations: 5.52103727549e-05
float comprehension: 0.00121321255003
line operations: 9.52025017378e-05
float comprehension: 0.000943885026522
line operations: 7.0782529173e-05
float comprehension: 0.000946716327689
转换为int然后除以1.0的速度要快得多,但是对我来说这是没有用的,因为我需要将数字保留在小数点后。
我看到了这个问题 ,开始尝试使用pandas.Series了,但是比我之前做的要慢。
In[38]: timeit("[float(i) for i in line[1:-2].split(',')]", "f=open('pathtofile');line=f.readline()", number=100)
Out[37]: 0.10676022701363763
In[39]: timeit("pandas.Series(line[1:-2].split(',')).apply(lambda x: float(x))", "import pandas;f=open('pathtofile');line=f.readline()", number=100)
Out[38]: 0.14640622942852133
如果可以加快文件速度,则可以选择更改文件格式,但是最好在读取结束时加快速度。
您将要使用numpy使用loadtxt创建一个浮点数组。 http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html
就像是:
import numpy
array = numpy.loadtxt('/path/to/data.file', dtype=<type 'float'>, delimiter=',')
如果由于空格而无法解决问题,您可能需要尝试使用'autostrip'选项的genfromtxt: http ://docs.scipy.org/doc/numpy/reference/genic/numpy.genfromtxt.html
这比手动或使用csvreader进行拆分/转换快得多。
首先,为了拆分行,可以使用csv
模块读取文件,该模块通过指定分隔符读取文件,并返回包含所有用逗号分隔的行的迭代器阅读器对象:
>>> import csv
>>> with open('filename', newline='') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=',')
... for row in spamreader:
#do stuff
然后,由于要将数字转换为浮点数,因为要对数字应用内置函数float
,因此,最好使用map
函数,这种函数在这种情况下比列表理解要好。
因此,对于每一行(当您使用csv阅读时,都可以):
... for row in spamreader:
numbers=map(float,row)
另外,关于使用熊猫及其性能,您可能会知道,当您处理的数据不是小数集时,类似pandas或Numpy的工具会更好,因为对于小数集,将python类型转换为C
类型的代价要比使用大熊猫的代价高。计算结果的优势。 有关更多信息,请阅读此问题以及完整的答案为什么列表理解比数组乘以numpy快得多?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.