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

时间:2019-04-01 05:52:03

标签: python-3.x pandas anaconda spyder

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

时的错误

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

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

我希望纠正索引错误。

1 个答案:

答案 0 :(得分:1)

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

在循环中,您永远不会检查idx是否小于len(array)。如果idx的末尾为零,则array会变大。