从需要.split(',')的字符串列表中高效创建多维数组

罗根乔希

我试图将当前for循环中的简单计算推numpy数组。在这种情况下,它是对以下形式的字符串列表的计算:

strings = ['12,34', '56,78'...]

我需要:

  1. 用逗号分隔符分割字符串,并产生两个整数,例如
    strings = [[12, 34], [56, 78]...]

  2. 仅将此嵌套列表过滤为仅满足某些任意条件的成员,例如,子列表中的两个数字均在特定范围内。

我正在尝试熟悉该numpy库,但是在不增加处理初始列表开销的情况下,我无法利用改进的计算速度。例如,我的本能是在创建数组之前在Python中进行split()andint()转换,但这最终要比简单for循环昂贵

除此之外,我似乎无法numpy在从初始列表创建的数组中组合完成此操作所需的各种操作。是否有理智的方法来执行此操作,还是因为数组仅使用一次这样的事情而导致丢失?

注:有一个旧的答案在这里那么就表明该字符串操作应在Python做,但它并不比运行时和现在也可能过时。

我的尝试比较:

import random
import datetime as dt
import numpy as np

raw_locs = [str(random.randint(1,100)) + ',' + str(random.randint(1,100)) 
            for x in xrange(100000)]

if __name__ =='__main__':

    # Python approach
    start1 = dt.datetime.now()
    results = []
    for point in raw_locs:
        lon, lat = point.split(",")
        lat = int(lat)
        lon = int(lon)
        if 0 <= lon <= 50 and 50 <= lat <= 100:
            results.append(point)
    end1 = dt.datetime.now()

    # Python list comprehension prior to numpy array
    start2 = dt.datetime.now()
    converted_list = [map(int, item.split(',')) for item in raw_locs]
    end2 = dt.datetime.now()

    # List comprehension + numpy array creation
    start3 = dt.datetime.now()
    arr = np.array([map(int, item.split(',')) for item in raw_locs])
    end3 = dt.datetime.now()

    start4 = dt.datetime.now()   
    results2 = arr[((0 <= arr[:,0]) & (arr[:,0] <= 50) 
                    & (50 <= arr[:,1]) & (arr[:,1] <= 100))]
    end4 = dt.datetime.now()

    # Print results
    print "Pure python for whole solution took:                {}".format(end1 - start1)
    print "Just python list comprehension prior to array took: {}".format(end2 - start2)
    print "Comprehension + array creation took:                {}".format(end3 - start3)
    print "Numpy actual calculation took:                      {}".format(end4 - start4)
    print "Total numpy time:                                   {}".format(end4 - start3)
安德拉斯·迪克(Andras Deak)

虽然我认为如果使用类似timeit模块的方法,计时会更精确,但我认为最大的问题是您正在解析字符串列表。Numpy的内置方法可以很好地与任何一种配合使用。请注意,在您的numpy情况下,输入的内容np.array()是包含其他内容的列表组合。

这是我的建议:将您的字符串列表加逗号以得到一个逗号分隔的字符串,用解析numpy.fromstring,然后将结果整形为两列:

arr = np.fromstring(','.join(raw_locs),sep=',').reshape(-1,2)

在笔记本电脑上添加了上述时间:

Pure python for whole solution took:                0:00:00.128965
Just python list comprehension prior to array took: 0:00:00.156092
Comprehension + array creation took:                0:00:00.186023
Join + fromstring took:                             0:00:00.035040
Numpy actual calculation took:                      0:00:00.001355
Total numpy time:                                   0:00:00.222454

请注意numpy.float64,即使您输入的是整数,上面的代码也会默认创建一个dtype数组。如果要使数组保持整数值,可以手动将dtype=np.int64关键字参数传递fromstring

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用.split()将字符串转换为数组(需要改进)

需要 Linq 表达式从对象字典(包含列表)创建字符串列表

Powershell -split 需要返回一个数字而不是字符串

我需要创建一个程序,该程序输入字符串列表,并输出整数,浮点数等

当不需要 str_split 字符时,如何取消设置行结果

需要一个用于正则表达式的字符串来将记录preg_split到数组中

有什么更有效的?将拆分字符串存储在数组中,或在需要时调用split方法

从指定索引处的字符串列表中删除不需要的子字符串

词典项目中(或字符串列表中)不需要的'\ n'字符

如何从python中的字符串列表中去除多个不需要的字符?

在熊猫数据框中高效存储大字符串列

在 Gremlin + Neptune 中,作为顶点的 Inject() 字符串列表需要很长时间

搜索字符串列表並查找需要更新的文件版本

如何使用string.split对具有特定格式的字符串列表进行排序?

需要数组列表的指导

Python字符串是不可变的,那么s.split()为什么返回新字符串列表

从多维数组项构建唯一的字符串列表

将多维numpy数组转换为字符串列表

rstrip() 字符串列中不需要的部分

错误:需要数组,但找到字符串

我需要创建一个多维数组

split-ValueError:需要多个值才能解压

在Java中使用.split需要一些简单的帮助

需要在处理时结束 Apache camel split

需要 str.split 函数来获取pair格式

在numpy中高效创建数组

在data.table中高效创建动态字符串

当我想在Python / Pandas中获取字符串列表的元素时,为什么需要使用.str?

正则表达式split:FutureWarning:split()需要非空模式匹配