You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NumPy数组填充相邻1间零值时的索引越界问题优化求助

Fixing Index Error & Correctly Filling Your NumPy Array

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 where data has a 1—this makes it easy to check gaps between consecutive 1s.
  • 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 first 1 to the second 1 with 1s.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:28:10