Skip to main content
 首页 » 编程设计

Python:快速循环遍历 np.array

2024年10月24日13jirigala

我有一个包含超过 1.5 亿个数据点的一维 np 数组,它是使用二进制数据文件上的 np.fromfile 填充的。

鉴于该数组,我需要为每个点添加一个值“val”,除非该点等于“x”。

此外,数组中的每个值,取决于它的值,将对应于我想存储在另一个列表中的另一个值。

变量解释:

** temps=np.arange(-30.00,0.01,0.01, dtype='float32')

** slr 是一个列表,temps 中的索引 0 对应于 slr 中的索引 0,依此类推。两个列表的长度相同

这是我当前的代码:

import sys 
import numpy as np 
 
with open("file.dat", "rb") as f: 
array = np.fromfile(f, dtype=np.float32) 
f.close() 
 
#This is the process below that I need to speed up  
 
T_SLR = np.array(np.zeros(len(array), dtype='Float64')) 
for i in range(0,len(array)): 
    if array[i] != float(-9.99e+08): 
        array[i] = array[i] - 273.15      
    if array[i] in temps: 
        index, = np.where(temps==array[i])[0] 
        T_SLR = slr[index] 
    else: 
        T_SLR[i] = 0.00 

请您参考如下方法:

你代码中最慢的一点是 O(n) 遍历 list in:

if array[i] in temps: 
    index, = np.where(temps==array[i])[0] 

由于temps不大,可以转成dict:

temps2 = dict(zip(temps, range(len(temps))) 

并使其成为 O(1):

if array[i] in temps2: 
    index = temps2[array[i]] 

也可以尽量避免for循环来加速。例如下面的代码:

for i in range(0,len(array)): 
    if array[i] != float(-9.99e+08): 
        array[i] = array[i] - 273.15 

可以这样做:

array[array!=float(-9.99e+08)] -= 273.15 

代码中的另一个问题是 float 比较。您不应该使用完全相等的运算符 == 或 !=,尝试使用带有公差的 numpy.isclose,或者通过乘以 100 将 float 转换为 int .