IndexError:索引91770超出了轴0的大小为91770的范围

问题描述 投票:0回答:1

以下代码给出了索引错误。我无法纠正它。因为它在数组[idx] == 0时显示错误

这是在Windows平台上使用Spyder在Anaconda软件中运行的。

def find_zero_runs(idx, array):
    #add 1 if True esle 0 and exit
    while array[idx] == 0:
        return 1 + find_zero_runs(idx+1, array)
    else:
        return 0
def avg_smoothing(bin_counts, cluster_bins):

#-------------FILL MISSING BINS with 0's------------------
    print('Filling missing pickup_bins with zeros...')
    bin_counts = fill_missing_bins(bin_counts, cluster_bins)

#------------------FIND ZERO INDICES----------------------
    print('finding zero indices...')
    zero_indices = np.where(bin_counts == 0)[0]

#------------------FIND ZERO RUNS-------------------------
    print('Finding zero runs...')
    zero_runs_dict = {}
    idx = 0  #pointer to zero_runs start_idx
    for z in zero_indices:
    #if c > 1, then iterate over the loop without computation
    #jump to the next zero_run index
        if idx == 0:
            c = find_zero_runs(z, bin_counts)
            zero_runs_dict[z] = c
        #print(f"({z}, {c})")
            idx = c
        idx -= 1

#------------------SMOOTHING USING ZERO RUNS------------------------------
    print('Smoothing using zero runs...')
    for idx in zero_runs_dict.keys():
    #beginning of new cluster
        if idx % num_time_bins == 0:
            start_idx = max(0, idx)  # pad the left index
            end_idx =  min(idx + zero_runs_dict[idx] + 1, len(bin_counts)) #pad the right index
            span = end_idx - start_idx #span is the num_zeros + (2 (or) 1)
        #print("boundary case ==> ", start_idx, end_idx)
        #calculate the average over the span, then distribute to respective elements
        #and assign to the indices
            bin_counts[start_idx : end_idx] = np.ones(span) * np.ceil(bin_counts[start_idx : end_idx].sum() / span)

        else:
            start_idx = max(0, idx - 1)  # pad the left index
            end_idx =  min(idx + zero_runs_dict[idx] + 1, len(bin_counts)) #pad the right index
            span = end_idx - start_idx
        #print(start_idx, end_idx)
            bin_counts[start_idx : end_idx] = np.ones(span) * np.ceil(bin_counts[start_idx : end_idx].sum() / span)

    print('Done...')
    return bin_counts

我希望纠正索引错误。

python-3.x pandas anaconda spyder
1个回答
1
投票

数组在python中是零基础的,即。大小为91770的数组的最后一个有效索引是91769。

在你的循环中,你永远不会检查idx是否小于len(array)。如果idx在其末尾有一连串零,那么array可以变得更大。

© www.soinside.com 2019 - 2024. All rights reserved.