當使用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