我有一个1-D np数组,有超过1.5亿个数据点,它是用np.fromfile文件在二进制数据文件上。在
给定那个数组,我需要给每个点加一个值'val',除非那个点等于'x'。在
此外,数组中的每个值(取决于它的值)将对应于另一个要存储在另一个列表中的另一个值。在
变量说明:
**临时工=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
使用
with open
时,不要自己关闭它。with
上下文自动执行此操作。我还更改了通用的array
名称,使其隐藏其他内容的风险更小(比如np.array
?)在首先不需要在}是可以的,但是我更喜欢使用
^{pr2}$np.array
中包装np.zeros
。它已经是一个数组。^如果data
是1d,则{shape
元组。在布尔索引/遮罩允许您同时对整个数组执行操作:
我需要改进
!=
测试。它适用于整数,但不适用于浮点。像np.abs(data+9.99e8)>1
这样的东西更好类似地,}执行冗余工作。在
in
也不是一个好的float测试。对于整数,in
和{假设中是冗余的。
temps
是1d,则np.where(...)
返回一个1元素元组。[0]
选择该元素,返回一个数组。然后,
在^{index, = np.where()
没有[0]
应该可以工作。在根据数组初始化的方式,
T_SLR[i]
已为0。不用再设置了。在但我认为我们也可以摆脱这种迭代。但我会把讨论留到以后再说。在
难怪做}很慢
array[i] in temps
和{我们可以把
in
去掉,看看where
如果没有匹配项,
where
返回一个空数组。在如果匹配项在列表的早期,则
in
可能比where
快,但如果不是更慢,则匹配在结束时,或者没有匹配。在四舍五入法:
我建议调整一下:
因为
temps
是排序的,所以可以使用np.searchsorted
并避免所有显式循环:代码中最慢的一点是对列表的O(n)遍历:
由于
^{pr2}$temps
不大,可以将其转换为dict:把它变成O(1):
您也可以尝试避免
for
循环来加快速度。例如,以下代码:可以这样做:
代码中的另一个问题是浮点比较。不应该使用完全相等的运算符},尝试使用带公差的
==
或{numpy.isclose
,或者通过乘以100将float转换为int。在相关问题 更多 >
编程相关推荐