我目前使用類似的代碼來確定比較
list_of_numbers = [29800.0, 29795.0, 29795.0, 29740.0, 29755.0, 29745.0]
high = 29980.0
lookback = 10
counter = 1
for number in list_of_numbers:
if (high >= number) \
and (counter < lookback):
counter = 1
else:
break
結果的counter大小將是7。然而,它對大型資料陣列來說非常繁重。所以,我一直在尋找解決方案并想出了np.argmax(),但似乎存在問題。例如以下內容:
list_of_numbers = [29800.0, 29795.0, 29795.0, 29740.0, 29755.0, 29745.0]
np_list = np.array(list_of_numbers)
high = 29980.0
print(np.argmax(np_list > high) 1)
這將得到輸出1,就像argmax假設.. 但我希望它得到輸出7。是否有另一種方法可以為 if 陳述句提供類似的輸出?
uj5u.com熱心網友回復:
您可以獲得一個布爾陣列,用于high >= number使用 NumPy 的位置:
list_of_numbers = [29800.0, 29795.0, 29795.0, 29740.0, 29755.0, 29745.0]
high = 29980.0
lookback = 10
boolean_arr = np.less_equal(np.array(list_of_numbers), high)
然后找到滿足代碼中條件的第一個False引數在哪里break。此外,要考慮反擊,您可以np.cumsum在布爾陣列上使用并找到滿足指定回溯幅度的第一個引數。因此,結果將是break_arr和lookback_lim之間的較小值:
break_arr = np.where(boolean_arr == False)[0][0] 1
lookback_lim = np.where(np.cumsum(boolean_arr) == lookback)[0][0] 1
result = min(break_arr, lookback_lim)
如果您list_of_numbers有沒有比你指定的任何較大值高限break_arr 或指定的回溯期超過價值np.cumsum(boolean_arr)為lookback_lim,上述代碼將卡住通過類似以下的錯誤,有關np.where:
索引錯誤:索引 0 超出軸 0 的范圍,大小為 0
可以由try-exceptorif陳述句處理,例如:
try:
break_arr = np.where(boolean_arr == False)[0][0] 1
except:
break_arr = len(boolean_arr) 1
try:
lookback_lim = np.where(np.cumsum(boolean_arr) == lookback)[0][0] 1
except:
lookback_lim = len(boolean_arr) 1
uj5u.com熱心網友回復:
你有你小于向后簽名,不是嗎?以下內容應與您的 for 回圈相同:
boolean_arr = (np_list <= high)
print(np.min([np.sum(boolean_arr[:np.where(boolean_arr==False)[0][0]]) 1, lookback]))
uj5u.com熱心網友回復:
可以使用 shift 完成回顧。cumcount 可用于獲得運行總數。查詢可以用作過濾器
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/368001.html
