python 读取大文本文件并存入numpy时过于费时的问题及猜测

因需要读取大文本文件(约有1,300,000行,40兆),并简单处理存入numpy数组中,运行过程中发现随读取数据的增加,耗费时间显著增加,稍作修改后运行速度显著提升,不解,记之,希望大家帮忙解惑。

初步猜测(未验证):在原始代码中对numpy数组进行了vstack,而这个过程可能对已有数组进行了类似遍历的操作,才会出现随数组中数据增加产生时间上的显著增加。

1.原始代码

此代码在前期运行较快,在运行接近4,500行左右时,速度开始逐步变慢,最后花了很长时间也没能运行出结果,不知是何种原因。

def readTXT1(txt_file, separator='	'):
    """
    读取单行文本数据(x y z i(or classification))
    :param txt_file: 待读取的文本
    :param separator: 待读取的文本中的分割符,如空格或制表符
    :return: 返回array数组,一行为一个数据
    """
    point = np.array([])
    with open(txt_file, 'r') as file:
        for line in file:
            point_tmp = line.split(separator)
            point_tmp = [x.strip() for x in point_tmp if x.strip() != '']
            point_tmp = list(map(float, point_tmp))
            point_one = np.array([point_tmp[0], point_tmp[1], point_tmp[2], point_tmp[3]])
            if np.shape(point)[0] > 0:
                point = np.vstack((point, point_one))
            else:
                point = np.array([point_one])
    print('% ', txt_file, 'has ', np.shape(point), 'points')
    return point

2.调整后代码

调整后先将数据存入list中,最后将list转换为array,此方案运行十分流畅,不足半分钟就已经完成读取与转化。相比原始代码只是少了一个判断和一个初始化array,但感觉问题应该不是出在此处,怀疑原始方案运行慢是因为叠置vstack。感觉只有在vstack过程中对已有数组进行了类似遍历的操作,才会出现随数组中数据增加产生时间上的显著增加。

def readTXT2(txt_file, separator='	'):
    """
    读取单行文本数据(x y z i(or classification))
    :param txt_file: 待读取的文本
    :param separator: 待读取的文本中的分割符,如空格或制表符
    :return: 返回array数组,一行为一个数据
    """
    all_points = []
    with open(txt_file, 'r') as file:
        for line in file:
            point_tmp = line.split(separator)
            point_tmp = [x.strip() for x in point_tmp if x.strip() != '']
            point_tmp = list(map(float, point_tmp))
            all_points.append(point_tmp[0:4])
    print('list:', len(all_points))
    point = np.array(all_points)
    print('% ', txt_file, 'has ', np.shape(point), 'points')
    return point
原文地址:https://www.cnblogs.com/waterbbro/p/14839217.html