基于首次出现的1修改二维数组对应位置元素的实现方法
Hey there! Let's solve this problem where we need to set all positions below the first occurrence of 1 in each column to 1. Here are two efficient approaches using NumPy:
Approach 1: Use Cumulative Maximum (Simplest & Fastest)
The most straightforward way is to leverage NumPy's np.maximum.accumulate function, which tracks the maximum value encountered so far as it iterates along a specified axis. Since 1 is greater than 0, this will automatically "lock" columns to 1 once the first 1 appears.
import numpy as np # Define your original array original_arr = np.array([[0, 0, 1, 1], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [1, 0, 1, 1], [1, 0, 1, 1], [0, 0, 0, 0], [1, 0, 0, 1]]) # Compute cumulative maximum along columns (axis=0) target_arr = np.maximum.accumulate(original_arr, axis=0) print(target_arr)
Output:
array([[0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [1, 0, 1, 1], [1, 0, 1, 1], [1, 0, 1, 1], [1, 0, 1, 1]])
Why this works: np.maximum.accumulate processes each column from top to bottom. For every position, it keeps the maximum value between the current element and all elements above it. Once a 1 is encountered, all subsequent positions in that column will stay 1 (since max(1, any value) is 1).
Approach 2: Manual Column-wise Processing (For Clarity)
If you want to explicitly see the logic of finding the first 1 and updating the column, you can iterate through each column directly:
import numpy as np original_arr = np.array([[0, 0, 1, 1], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [1, 0, 1, 1], [1, 0, 1, 1], [0, 0, 0, 0], [1, 0, 0, 1]]) target_arr = original_arr.copy() for col_idx in range(original_arr.shape[1]): # Get the current column column = original_arr[:, col_idx] # Find the first index where the value is 1 first_one_pos = np.argmax(column == 1) # Check if there actually is a 1 in the column if column[first_one_pos] == 1: # Set all rows from first_one_pos down to 1 target_arr[first_one_pos:, col_idx] = 1 print(target_arr)
This will produce the same output as the first approach. It's a bit more code, but it makes the underlying logic explicit: find the first 1 in each column, then overwrite everything below it.
内容的提问来源于stack exchange,提问作者ZPython

