有没有更快的方法将字符串转换为python中的浮点数?

时间:2015-10-09 09:41:03

标签: python python-2.7 optimization casting

我正在从文件中读取数字并将它们转换为浮点数。数字看起来像这样。

<div ng-repeat="item in listItemsFiltered = (listItems | filter:{name: search.Name, number: search.Number}) | orderBy:'Name' | startFrom: currentPage*pageSize | limitTo: pageSize">

我用逗号分隔每一行,然后通过列表理解创建浮动列表。

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

转换为int然后除以1.0会快得多,但在我的情况下没用,因为我需要保留小数点后面的数字。

我看到了this question并开始使用pandas.Series,但这比我以前做的要慢。

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

如果可以加快文件的格式,可以选择更改文件的格式,但在阅读端加快速度会更好。

2 个答案:

答案 0 :(得分:3)

您将要使用numpy使用loadtxt创建一个浮点数组。 http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html

类似的东西:

C

如果由于空格不起作用,您可能想尝试使用'autostrip'选项的genfromtxt: http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html

这比手动分割/转换或使用csvreader快得多。

答案 1 :(得分:0)

首先,为了获得分割你的行,你可以使用csv模块来读取文件,该文件通过指定分隔符读取文件并返回迭代器读取器对象,其中包含由逗号分割的所有行: / p>

>>> 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类型转换为{{1类型不仅仅是计算结果的优势。有关详细信息,请阅读此问题和完整答案Why list comprehension is much faster than numpy for multiplying arrays?