NumPy数组填充相邻1间零值时的索引越界问题优化求助
Hey there! Let's break down why you're hitting that index error and fix your array-filling logic to match your desired output.
Why the Index Error Happens
Your original code checks data[i+3], but when i gets close to the end of your array (which has 38 elements, indices 0 to 37), i+3 will exceed 37 (for example, when i=35, i+3=38 which is out of bounds). That's exactly what's triggering the IndexError.
Also, your current logic only handles cases where two 1s are exactly 3 positions apart (with 2 zeros in between), but it misses cases where there's just 1 zero between 1s. Let's fix both issues.
Solution Code
Here's a robust approach that avoids index errors and covers all cases where 1s are separated by 1 or 2 zeros:
import numpy as np # Your original data array data = np.array([0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0]) # Get all indices where the value is 1 ones_indices = np.where(data == 1)[0] # Iterate through consecutive pairs of 1s for i in range(len(ones_indices) - 1): current = ones_indices[i] next_one = ones_indices[i+1] # Check if the gap between 1s is <=3 (meaning 1 or 2 zeros in between) if next_one - current <= 3: # Fill all positions from current to next_one with 1 data[current:next_one+1] = 1 print(data)
What This Does
- Finding 1s:
np.where(data == 1)[0]gives us a list of all indices wheredatahas a1—this makes it easy to check gaps between consecutive1s. - Checking Gaps: We loop through each pair of adjacent
1s. If the distance between them is 3 or less (so 1 or 2 zeros in between), we fill the entire range from the first1to the second1with1s. - Safe Slicing: Using NumPy slicing (
data[current:next_one+1]) automatically handles array bounds, so we never try to access an index that doesn't exist.
Output
Running this code will give you exactly the result you want:
array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
Bonus: Handling the End-of-Array 1
Your original code tried to handle a 1 at the end of the array, but with this approach, we don't need that check—since we only look at pairs of consecutive 1s, the last 1 has no next 1 to pair with, so nothing gets done to it (which is exactly what you want).
内容的提问来源于stack exchange,提问作者Karo

