32

我对 python 和 numpy 都是新手。我运行了我编写的代码,我收到了这条消息:'index 0 is out of bounds for axis 0 with size 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
4

3 回答 3

36

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 列的二维数组。

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

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

同样,在调试此类问题时,您应该做的第一件事是打印可疑变量的shape(可能还有dtype)。

应用于pandas

解决错误:

  1. 使用try-except
  2. 验证数组的大小不为 0
    • if x.size != 0:
于 2017-01-05T19:02:24.630 回答
8

这是IndexErrorpython中的一个,这意味着我们正在尝试访问张量中不存在的索引。下面是一个非常简单的例子来理解这个错误。

# 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位置)(即它不存在,因为我们有一个 size 数组0)。

In [19]: arr.size * arr.itemsize  
Out[19]: 0

所以,本质上,这样的数组是没有用的,不能用来存储任何东西。因此,在您的代码中,您必须遵循回溯并寻找您正在创建大小的数组/张量的位置0并修复它。

于 2020-01-12T00:37:44.037 回答
7

本质上,这意味着您没有尝试引用的索引。例如:

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)

会给我你所指的错误,因为我没有告诉熊猫我的数据框有多长。而如果我执行完全相同的代码但我确实分配了索引长度,我不会收到错误消息:

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)

希望这能回答你的问题!

于 2018-04-27T21:29:36.433 回答