索引超出范围(Python) [英] Index out of bounds (Python)

查看:212
本文介绍了索引超出范围(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些要汇总的数据,但是索引超出范围,我似乎无法弄清楚为什么.这是我的代码:

I have some data that I would like to aggregate, but I'm getting the index out of bounds error, and I can't seem to figure out why. Here's my code:

if period == "hour":
    n=3
    tvec_a=np.zeros([24,6])
    tvec_a[:,3]=np.arange(0,24)
    data_a=np.zeros([24,4])
elif period == "day":
    n=2
    tvec_a=np.zeros([31,6])
    tvec_a[:,2]=np.arange(1,32)
    data_a=np.zeros([31,4])
elif period == "month":
    n=1
    tvec_a=np.zeros([12,6])
    tvec_a[:,1]=np.arange(1,13)
    data_a=np.zeros([12,4])
elif period == "hour of the day":
    tvec_a=np.zeros([24,6])
    tvec_a[:,3]=np.arange(0,24)
    data_a=np.zeros([24,4])
i=0
if period == "hour" or period == "day" or period == "month":
    while i <= np.size(tvec[:,0]):
        data_a[tvec[i,n],:]=data_a[tvec[i,n],:]+data[i,:]
        i=i+1
        if i > np.size(tvec[:,0]):
            break

如果我将日期设为月或月,则只会收到错误.小时工作正常. (代码是接受tvec,数据和周期的函数的一部分)

I only get the error if I make period day or month. Hour works just fine. (The code is part of a function that takes in a tvec, data and period)

Traceback (most recent call last):

  File "<ipython-input-23-7fb910c0f29b>", line 1, in <module>
    aggregate_measurements(tvec,data,"month")

  File "C:/Users/Julie/Documents/DTU - design og innovation/4. semester/Introduktion til programmering og databehandling (Python)/Projekt 2 electricity/agg_meas.py", line 33, in aggregate_measurements
    data_a[tvec[i,n],:]=data_a[tvec[i,n],:]+data[i,:]

IndexError: index 12 is out of bounds for axis 0 with size 12

通过在tvec的值上写入负1来解决此问题:

Fixed it, by writing minus 1 on the value from the tvec:

data_a[tvec[i,n]-1,:]=data_a[tvec[i,n]-1,:]+data[i,:]

推荐答案

由于列表的索引为0,因此只能在12个元素的数组上上升到索引11.

Since lists are 0-indexed, you can only go up to index 11 on a 12-element array.

因此,while i <= np.size(tvec[:,0])应该应该是while i < np.size(tvec[:,0]).

额外注意:break是不必要的,因为无论如何只要满足条件,while循环就会停止.

Extra Note: The break is unnecessary because the while loop will stop once the condition is met anyway.

这篇关于索引超出范围(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆