python-3.x - 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 中是从零开始的,即。大小为 91770 的数组的最后一个有效索引是 91769。
在您的循环中,您永远不会检查是否idx
小于len(array)
. 如果末尾有一系列零,idx
则可以变大。array
推荐阅读
- node.js - UnhandledPromiseRejectionWarning:错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头
- python - 如何使用 pyplot 在线绘图?
- android - 什么是在 Android Studio 项目中创建 generated.xml google_maps_key?
- python - 我有以下测试代码。我怎样才能使这个条件为真
- java - 我的 OnNavigationItemSelectedListener kotlin android 有什么问题?
- java - 使用 Jackson 将 Xml 反序列化到列表失败
- react-native - 弃用 componentWillMount 后如何获取异步数据?
- javascript - Firebase 查询 startAt 始终返回至少一项
- java - Azure 存储 Java API:检查存储帐户是否支持安全传输或不使用 java SDK
- javascript - ReactJs中组件的“功能未定义”onClick函数内联?