'索引0超出尺寸0的轴0的范围是什么意思?

问题描述 投票:7回答:3

我对python和numpy都是陌生的。我运行了自己编写的代码,并收到以下消息:'索引0超出大小为0的轴0的范围'如果没有上下文,我只想弄清楚这是什么意思。问这个问题可能很愚蠢,但是它们对于轴0和尺寸0的含义是什么?索引0表示数组中的第一个值..但我无法弄清楚轴0和大小0的含义。

“数据”是一个文本文件,两列中有很多数字。

x = np.linspace(1735.0,1775.0,100)
column1 = (data[0,0:-1]+data[0,1:])/2.0
column2 = data[1,1:]
x_column1 = np.zeros(x.size+2)
x_column1[1:-1] = x
x_column1[0] = x[0]+x[0]-x[1]
x_column1[-1] = x[-1]+x[-1]-x[-2]
experiment = np.zeros_like(x)
for i in range(np.size(x_edges)-2):
    indexes = np.flatnonzero(np.logical_and((column1>=x_column1[i]),(column1<x_column1[i+1])))
    temp_column2 = column2[indexes]
    temp_column2[0] -= column2[indexes[0]]*(x_column1[i]-column1[indexes[0]-1])/(column1[indexes[0]]-column1[indexes[0]-1])
    temp_column2[-1] -= column2[indexes[-1]]*(column1[indexes[-1]+1]-x_column1[i+1])/(column1[indexes[-1]+1]-column1[indexes[-1]])
    experiment[i] = np.sum(temp_column2)   
return experiment
python numpy indexing error-handling index-error
3个回答
10
投票
numpy中,索引和维度编号从0开始。因此axis 0表示第一维。同样在numpy中,维度的长度(大小)可以为0。最简单的情况是:

In [435]: x = np.zeros((0,), int) In [436]: x Out[436]: array([], dtype=int32) In [437]: x[0] ... IndexError: index 0 is out of bounds for axis 0 with size 0

[如果是x = np.zeros((0,5), int),也就是0行5列的2d数组,我也得到它。

所以在代码中的某个地方,您正在创建一个大小为0的第一轴数组。

问错误时,您应该告诉我们错误发生在哪里。

此外,当调试此类问题时,您应该做的第一件事是打印可疑变量的shape(也许是dtype


2
投票
本质上,这意味着您没有要引用的索引。例如:

df = pd.DataFrame() df['this']=np.nan df['my']=np.nan df['data']=np.nan df['data'][0]=5 #I haven't yet assigned how long df[data] should be! print(df)

将给我您所指的错误,因为我没有告诉Pandas我的数据框有多长时间。而如果我执行完全相同的代码,但是我确实分配了索引长度,则不会收到错误:

df = pd.DataFrame(index=[0,1,2,3,4]) df['this']=np.nan df['is']=np.nan df['my']=np.nan df['data']=np.nan df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem! print(df)

希望能回答您的问题!

0
投票
这是python中的IndexError,这意味着我们正在尝试访问张量中不存在的索引。下面是一个非常简单的示例来了解此错误。

# create an empty array of dimension `0` In [14]: arr = np.array([], dtype=np.int64) # check its shape In [15]: arr.shape Out[15]: (0,)

使用此数组arr,如果我们现在尝试将任何值分配给某个索引,例如,如下所示,则分配给索引0

In [16]: arr[0] = 23

然后,我们将得到一个IndexError,如下所示:


IndexError Traceback (most recent call last) <ipython-input-16-0891244a3c59> in <module> ----> 1 arr[0] = 23 IndexError: index 0 is out of bounds for axis 0 with size 0
原因是我们试图访问一个不存在的索引(这里是0 

th位置)(即,由于我们有一个大小为0的数组,所以不存在)。

In [19]: arr.size * arr.itemsize Out[19]: 0
因此,从本质上讲,这样的数组是没有用的,不能用于存储任何东西。因此,在代码中,您必须遵循追溯,并在其中创建大小为0的数组/张量的位置并进行修复。
© www.soinside.com 2019 - 2024. All rights reserved.