python - 索引越界 (Python)

标签 python indexing bounds out

我有一些想要聚合的数据,但出现索引越界错误,而且我似乎不明白为什么。这是我的代码:

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、数据和周期的函数的一部分)

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 来修复它:

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

最佳答案

由于列表的索引为 0,因此在 12 元素数组中只能向上移动到索引 11。

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

额外说明:break没有必要,因为一旦条件满足,while 循环就会停止。

关于python - 索引越界 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43775448/

相关文章:

mysql - 链接表和 substring_index 的命名约定

python - 在列表中查找部分字典元素的索引

ios - imageview 和 image aspect fit ratio 之间的差异

ios - 什么时候调用layoutSubviews?

python - pyspark 使用 partitionby 对数据进行分区

python 请求和 TLS

indexing - Intershop 7.10 代码生成器备用键生成 - NONUNIQUE

python - Binance python api查询全局账户余额

Python Selenium - 无法通过数据标题的属性定位元素

android - 观看动画不会改变触摸区域