IndexError: индекс 91770 выходит за пределы оси 0 с размером 91770 - PullRequest
0 голосов
/ 01 апреля 2019

Следующий код выдает ошибку индекса. Я не могу это исправить. Как он показывает ошибку в строке, а массив [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

Я хочу, чтобы ошибка индекса была исправлена.

1 Ответ

1 голос
/ 01 апреля 2019

Массивы начинаются с нуля в python, т.е. последний действительный индекс для массива размером 91770 - 91769.

В вашем цикле вы никогда не проверяете, меньше ли idx, чем len(array). idx может увеличиться, если array имеет ряд нулей в конце.

...