我正在从文件中读取数字并将它们转换为 float 。数字如下所示。
1326.617827, 1322.954823, 1320.512821, 1319.291819...
我用逗号分隔每一行,然后通过列表理解创建 float 列表。
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 速度要快得多,但对我来说没有用,因为我需要保留小数点后的数字。
我看到了this question并尝试使用 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 创建 float 数组。 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/generated/numpy.genfromtxt.html
这比手动或使用 csvreader 拆分/转换要快得多。
关于python - 在 python 中是否有更快的方法将字符串转换为 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33034912/