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

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

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

1.原始代码

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

def readTXT1(txt_file, separator='\t'):
    """
    读取单行文本数据(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='\t'):
    """
    读取单行文本数据(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

 

要将Python字典存NumPy数组中,可以使用NumPy的save函数将字典保存为.npy文件,然后使用load函数加载.npy文件。以下是一个示例代码: ``` import numpy as np my_dict = {'a': {1, 2, 3}, 'b': {4, 5, 6}} np.save('dict.npy', my_dict) loaded_dict = np.load('dict.npy', allow_pickle=True).item() print("Original dictionary:", my_dict) print("Loaded dictionary:", loaded_dict) ``` 这段代码将字典`my_dict`保存为名为'dict.npy'的.npy文件,然后使用`np.load`函数加载.npy文件并将其转换回字典格式。最后打印出原始字典和加载后的字典。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [numpy保存和读取dictionary字典 python](https://blog.csdn.net/weixin_45366564/article/details/104667150)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [python使用numpy保存字典格式的数据](https://blog.csdn.net/weixin_35757704/article/details/124921501)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值