首页 > 解决方案 > IndexError:索引 91770 超出轴 0 的范围,大小为 91770

问题描述

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

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

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.xpandasanacondaspyder

解决方案


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

在您的循环中,您永远不会检查是否idx小于len(array). 如果末尾有一系列零,idx则可以变大。array


推荐阅读