使用同形状掩码处理NumPy数组及构造衍生掩码的技术咨询
Hey there! Let's tackle your two NumPy masking questions one by one—super straightforward once you know the right vectorized tricks (no slow loops needed!):
You have two main options here, depending on whether you want to extract unmasked elements or keep the original array shape with masked markers:
Option 1: Boolean Indexing (extract unmasked elements)
This directly pulls out all elements where the mask isTrueinto a 1D array—great if you just need the values without preserving shape.import numpy as np # Example array and mask arr = np.array([[10, 20, 30], [40, 50, 60]]) mask = np.array([[False, True, False], [True, False, True]]) unmasked_vals = arr[mask] print(unmasked_vals) # Output: [20 40 60]Option 2: Masked Array (preserve shape)
Usenumpy.ma.masked_arrayto create an array that keeps the original shape but marks masked elements as invalid. This is perfect for keeping context around your data.masked_arr = np.ma.masked_array(arr, mask=mask) print(masked_arr) # Output: # [[10 -- 30] # [-- 50 --]]
Your requirement is: m2[i,j] = True if and only if j >= 0 (which is always true for valid indices) and m1[i, j+1] == True.
This is equivalent to shifting each row of m1 to the right by 1 position, then padding the rightmost column with False (since for the last column of m2, j+1 would be out of bounds for m1, so those values must be False).
Here's the elegant, vectorized implementation—no loops, just fast NumPy operations:
m1 = np.array([[False, True, False], [True, False, True]]) # Step 1: Take all columns except the last one (this shifts j+1 to j position) # Step 2: Pad a column of False on the right to match m1's shape m2 = np.pad(m1[:, :-1], ((0, 0), (0, 1)), mode='constant', constant_values=False) print(m2) # Output: # [[True False False] # [False True False]]
Why this works:
m1[:, :-1]slices each row to exclude the final element—so for each row, the element at positionjin this slice is exactlym1[i, j+1]from the original mask.np.pad(...)adds a singleFalsevalue to the end of each row, ensuringm2has the same shape asm1and handles the out-of-bounds case correctly.
This approach is efficient even for large arrays because it uses NumPy's built-in vectorized operations, which are implemented in C under the hood.
内容的提问来源于stack exchange,提问作者kirstain.yuval

