python - 加速Python函数处理数据段以空格分隔的文件

标签 python numpy performance

我需要处理数据段以空格分隔的文件,例如:

93.18 15.21 36.69 33.85 16.41 16.81 29.17 
21.69 23.71 26.38 63.70 66.69 0.89 39.91 
86.55 56.34 57.80 98.38 0.24 17.19 75.46 
[...]
1.30 73.02 56.79 39.28 96.39 18.77 55.03

99.95 28.88 90.90 26.70 62.37 86.58 65.05 
25.16 32.61 17.47 4.23 34.82 26.63 57.24 
36.72 83.30 97.29 73.31 31.79 80.03 25.71 
[...]
2.74 75.92 40.19 54.57 87.41 75.59 22.79

.
.
.

为此,我使用以下函数。 在每次调用中我都会获得必要的数据,但我需要加快代码速度。

有没有更有效的方法?

编辑:我将使用实现改进的更改来更新代码

原件:

def get_pos_nextvalues(pos_file, indices):
    result = []
    for line in pos_file:
        line = line.strip()
        if not line:
            break
        values = [float(value) for value in line.split()]
        result.append([float(values[i]) for i in indices])
    return np.array(result)

新:

def get_pos_nextvalues(pos_file, indices):
    result = ''
    for line in pos_file:
        if len(line) > 1:
            s = line.split()
            result += ' '.join([s [i] for i in indices])
        else:
            break
    else:
        return np.array([])
    result = np.fromstring(result, dtype=float, sep=' ')
    result = result.reshape(result.size/len(indices), len(indices))
    return result

.

pos_file = open(filename, 'r', buffering=1024*10)

[...]

while(some_condition):
    vs = get_pos_nextvalues(pos_file, (4,5,6))
    [...]

加速 = 2.36

最佳答案

第一步不将 float 转换为 float 。不过,我建议首先profile your code然后尝试优化瓶颈部分。

我知道您已经更改了原始代码,但是

values = [value for value in line.split()]

也不是一件好事。如果这就是您的意思,只需编写 values = line.split() 即可。

看看你如何使用 NumPy,我建议一些 methods of file reading that are demonstrated in their docs .

关于python - 加速Python函数处理数据段以空格分隔的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2311376/

相关文章:

python - Pandas:将数组列转换为 numpy 矩阵

python - 从一组段范围构建掩码

performance - Oracle 主键与索引 NOT IN 性能

python - 用于创建 AMI 的 Boto3 create_image - 仅保 stub 卷

python - RDD.take 不起作用

python - 执行 "import tensorflow.keras.utils.np_utils"时出错

python - 绘制 sum(matrix,axis=0) 并用求和所需的非零元素的行索引标记该图

python - 选择 numpy 数组的列

arrays - MATLAB 中的逻辑数组与数值数组

python - 绘制一个显示直到下次单击的形状