Seo*_*ong 7 python indexing error-handling numpy index-error
我是python和numpy的新手.我运行了一个我编写的代码,我收到了这条消息:'索引0超出了0号轴的大小为0'没有上下文,我只是想弄明白这意味着什么..问这个可能很傻但它们的轴0和尺寸0是什么意思?index 0表示数组中的第一个值..但我无法弄清楚0和0的意思.
'data'是一个文本文件,在两列中有许多数字.
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
Run Code Online (Sandbox Code Playgroud)
hpa*_*ulj 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
Run Code Online (Sandbox Code Playgroud)
如果x = np.zeros((0,5), int)是一个包含0行和5列的2d数组,我也会得到它.
因此,在代码中的某个位置,您将创建一个第一轴大小为0的数组.
在询问错误时,您应该告诉我们错误发生的位置.
此外,在调试此类问题时,您应该做的第一件事就是打印可疑变量shape(可能还有dtype).
小智 5
从本质上讲,这意味着您没有要引用的索引。例如:
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)
Run Code Online (Sandbox Code Playgroud)
会给我你所指的错误,因为我没有告诉 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)
Run Code Online (Sandbox Code Playgroud)
希望这能回答你的问题!
这是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,)
Run Code Online (Sandbox Code Playgroud)
有了这个数组arr,如果我们现在尝试将任何值分配给某个索引,例如分配给索引,0如下例所示
In [16]: arr[0] = 23
Run Code Online (Sandbox Code Playgroud)
然后,我们将得到一个IndexError,如下所示:
Run Code Online (Sandbox Code Playgroud)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
Run Code Online (Sandbox Code Playgroud)
所以,本质上,这样的数组是无用的,不能用于存储任何东西。因此,在您的代码中,您必须遵循回溯并寻找创建大小数组/张量的位置0并修复它。
| 归档时间: |
|
| 查看次数: |
40782 次 |
| 最近记录: |