我正在尋找更多 pythonic / numpy 的方法來解決這個問題。這是非常低效的,我正在對數百萬個值執行此操作。
輸入:
pos_all = np.array([1,2,3,4,5])
var_stat = np.array([True, True, False, True, True])
below_missing_threshold([False, False, True, False])
pos_all包含一個值陣列。中的值的狀態pos_all包含在 中var_stat。如果var_stat值為,則陣列True中存在該值的相應布林值。below_missing_threshold如果var_stat是False,則沒有對應的值,below_missing_threshold但我們可以為其賦值True。
這是我目前的解決方案:
accessible = []
for i in range(0, len(pos_all)):
if len(pos_all) != len(var_stat):
sys.exit("Warning: All Position array does not match variant status array")
if len(pos) != len(below_missing_threshold):
sys.exit("Warning: Varaint Postion array does not match filter status array")
else:
site = pos_all[i]
is_var = var_stat[i]
if is_var == True:
#Find the index of the variant
var_i = np.where(pos == site)[0][0]
#Check if it passes filter
if below_missing_threshold[var_i] == False:
accessible.append(False)
else:
accessible.append(True)
else:
accessible.append(True)
函式回傳:
is_acessible = [False, False, True, True, False]
uj5u.com熱心網友回復:
IIUC,您可以通過使用np.ones_like. 然后用于var_stat選擇必須重新分配的值below_missing_threshold
is_accessible = np.ones_like(pos_all, dtype=bool)
is_accessible[var_stat] = below_missing_threshold
print(is_accessible)
# [False False True True False]
uj5u.com熱心網友回復:
還有另一種方法:
above_thresh_idx = np.where(var_stat==False)
var_stat[np.where(var_stat==True)]=below_missing_threshold
var_stat[above_thresh_idx] = True
uj5u.com熱心網友回復:
IIUC,您可以通過以下方式執行此操作np.insert(但索引是最佳選擇):
F = np.where(var_stat == False)[0]
F_mod = np.insert(below_missing_threshold, F - np.arange(F.size), False)
result = var_stat == F_mod
# [False False True True False]
或作為單行的另一種替代方式:
result = var_stat == np.insert(below_missing_threshold, np.flatnonzero(var_stat==0)
- np.count_nonzero(var_stat==0), False)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474467.html
下一篇:預分配或更改向量的大小
