When using with open, don't close it yourself. The with context does that automtically. I'm also changing the generic array name with something that has less risk of shadowing something else (like np.array?)
with open("file.dat", "rb") as f:
data = np.fromfile(f, dtype=np.float32)
First no need to wrap np.zeros in np.array. It already is an array. len(data) is ok if data is 1d, but I prefer to work the shape tuple.
T_SLR = np.zeros(data.shape, dtype='Float64')
Boolean indexing/masking lets you act on the whole array at once:
mask = data != -9.99e8 # don't need `float` here
# using != test with floats is poor idea
data[mask] -= 273.15
I need to refine the != test. It is ok for integers, but not for floats. Something like np.abs(data+9.99e8)>1 is better
Similarly in is not a good test with floats. And with integers, the in and where perform redundant work.
Assuming temps is 1d, the np.where(...) returns a 1 element tuple. [0] selects that element, returning an array. The , is then redundant in index,. index, = np.where() without the [0] should have worked.
T_SLR[i] is already 0 by how the array was initialized. No need to set it again.
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
But I think we can get rid of this iteration as well. But I'll leave that discussion for later.
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,)
No wonder doing array[i] in temps and np.where(temps==array[i]) is slow
We can cut out the in with a look at the 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),)
If there isn't a match where returns an empty array.
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 can be faster than where if the match is early in the list, but as slow, if not more so, it the match is at then end, or there is no match.
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
A rounding approach:
In [487]: (np.round(temps,2)/.01).astype(int)
Out[487]: array([-3000, -2999, -2998, ..., -2, -1, 0])
I'd suggest tweaking:
T_SLR = -np.round(data, 2)/.01).astype(int)
tempsintended to get all temperatures between -30 and 0, or do you really want just the samples that don't have a sub-hundredths fractional part going intoT_SLR?