假設我有一個要從中洗掉特定元素的 numpy 陣列。
# data = np.array([ 97 32 98 32 99 32 100 32 101])
# collect indices where the element locate
indices = np.where(data==32)
without_32 = np.delete(data, indices)
# without_32 become [ 97 98 99 100 101]
現在,假設我想恢復陣列(因為我已經有了應該放置值的索引32)。
restore_data = np.insert(without_32, indices[0], 32)
但它給了IndexError: index 10 is out of bounds for axis 0 with size 9. 還有其他方法可以實作嗎?
更新
似乎洗掉元素后,我需要對索引進行一些調整,例如
restore_data = np.insert(without_32, indices[0]-np.arange(len(indices[0])), 32)
但是我可以概括一下嗎?不僅喜歡32而且還trace 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47。我的意思是我想以一種有效的方式追蹤相同32-47的方式。
uj5u.com熱心網友回復:
我的替代方案:
#define a mask
mask = data==32
mask #array([False, True, False, True, False, True, False, True, False])
#filter
without_32 = data[~mask]
without_32 #array([ 97, 98, 99, 100, 101])
然后,如果您想擁有原始資料:
restore_data = np.ones_like(mask, dtype=int)*32
restore_data[~mask] = without_32
restore_data
輸出:
array([ 97, 32, 98, 32, 99, 32, 100, 32, 101])
在實踐中,您正在生成一個32長度等于mask(并且顯然是)的常量陣列,然后用陣列data填充掩碼所在False的位置(位置data!=32)without_32
更新
為了回答您的更新:
data = np.random.randint(20, 60, size=20)
#array([47, 39, 29, 45, 21, 44, 48, 27, 21, 25, 47, 59, 58, 53, 46, 36, 34, 57, 36, 54])
mask = (data>=32)&(data<=47) #the values you want to remove
clean_array = data[~mask] #data you want to retain
removed_data = data[mask] #data you want to remove
現在你可以del data了,你可以做任何你想做的事情clean_array,當你需要重建原始陣列時,你只需:
restore_data = np.zeros_like(mask, dtype=int)
restore_data[~mask] = clean_array
restore_data[mask] = removed_data
#array([47, 39, 29, 45, 21, 44, 48, 27, 21, 25, 47, 59, 58, 53, 46, 36, 34, 57, 36, 54])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/471435.html
上一篇:分配給雙索引numpy陣列
