当使用with open
,不要自行将其关闭。 with
上下文自动执行。我也改变了通用array
名的东西有阴影别的东西的风险较小(如np.array
?)
with open("file.dat", "rb") as f:
data = np.fromfile(f, dtype=np.float32)
首先没有必要np.array
包np.zeros
。它已经是一个数组。 len(data)
是确定的,如果data
是一维的,但我更喜欢的工作shape
元组。
T_SLR = np.zeros(data.shape, dtype='Float64')
布尔索引/掩蔽让你成为整个阵列上一次:
mask = data != -9.99e8 # don't need `float` here
# using != test with floats is poor idea
data[mask] -= 273.15
我需要细化!=
测试。整数可以,但不适用于浮点数。类似np.abs(data+9.99e8)>1
是更好的
同样in
是不是一个很好的测试与浮动。并与整数时,in
和where
执行多余的工作。
假设temps
是图1D中,np.where(...)
返回1个元素的元组。 [0]
选择该元素,返回一个数组。 ,
然后在index,
中是多余的。 index, = np.where()
没有[0]
应该已经工作。
T_SLR[i]
已经被数组的初始化为0了。无需重新设置。
for i in range(0,len(array)):
if array[i] in temps:
index, = np.where(temps==array[i])[0]
T_SLR = slr[index]
else:
T_SLR[i] = 0.00
但我认为我们也可以摆脱这种迭代。但我稍后会讨论这个问题。
In [461]: temps=np.arange(-30.00,0.01,0.01, dtype='float32')
In [462]: temps
Out[462]:
array([ -3.00000000e+01, -2.99899998e+01, -2.99799995e+01, ...,
-1.93138123e-02, -9.31358337e-03, 6.86645508e-04], dtype=float32)
In [463]: temps.shape
Out[463]: (3001,)
难怪做array[i] in temps
和np.where(temps==array[i])
缓慢
我们可以切出in
与一看where
In [464]: np.where(temps==12.34)
Out[464]: (array([], dtype=int32),)
In [465]: np.where(temps==temps[3])
Out[465]: (array([3], dtype=int32),)
如果没有匹配where
回报一个空阵列。
In [466]: idx,=np.where(temps==temps[3])
In [467]: idx.shape
Out[467]: (1,)
In [468]: idx,=np.where(temps==123.34)
In [469]: idx.shape
Out[469]: (0,)
in
可如果比赛是在列表中早于where
快,但慢,如果不是更多的话,它的比赛时间是再结,或没有匹配。
In [478]: timeit np.where(temps==temps[-1])[0].shape[0]>0
10000 loops, best of 3: 35.6 µs per loop
In [479]: timeit temps[-1] in temps
10000 loops, best of 3: 39.9 µs per loop
一个四舍五入的方法:
In [487]: (np.round(temps,2)/.01).astype(int)
Out[487]: array([-3000, -2999, -2998, ..., -2, -1, 0])
我建议的调整:
T_SLR = -np.round(data, 2)/.01).astype(int)
看起来您的传感器可能只会返回0.01度增量值。真的吗?而且,如果是这样的话,选择'temps'是为了让所有的温度在-30到0之间,还是你真的想要那些没有百分之一小数的样本进入'T_SLR'? –
是的,临时工应该有-30到0合并每0.01。那里的每个温度值都对应于列表slr中的slr值。 T_SLR是一个新的列表(将具有与'数组'相同的长度)。数组的值与临时值进行比较,如果它的温度低于索引值。该索引用于从slr中提取值。然后附加到T_SLR – user2938093